Javascript prompt() - cancel button to terminate the function

You should explicitly check for null as the return value (using triple-equals) and return when this is the result.

var result = prompt("OK?");
if (result === null) {
    return;
}

This allows you to distinguish from the empty string, which is what's returned when the user clicks OK but enters no content.


prompt returns a string if the user presses OK ('' being with no value submitted). If the user pressed Cancel, null is returned. All you need to do is check whether the value is null:

function doSomething() {
    var input;
    input = prompt('Do something?');
    if (input === null) {
        return; //break out of the function early
    }
    switch (input) {
    case 'fun':
        doFun();
        break;
    case 'boring':
        beBoring();
        break;
    }
}

One substantial problem with handling the result of 'prompt' is that Safari (at least version 9.1.2) returns "" instead of null when "Cancel" is clicked. This means that: if(result==null) return; does not work, and you cannot distinguish between entry of a null string, and cancellation.