user2502053
user2502053

Reputation: 69

Terminate function execution using confirm()

Using the confirm() method, how can you stop function execution after a FALSE return WITHOUT a conditional? Here is an example call and an abbreviated function:

<form>
    <input value="Play" type="button" onClick="LetsPlay();">
</form> 

function LetsPlay()
{

    confirm("Request permission to play Abracadabra!");
    prompt("Pick a number between 10 and 20");
    //more actions to follow
}

Upvotes: 1

Views: 69

Answers (1)

Patrick McElhaney
Patrick McElhaney

Reputation: 59301

You could use short-circuit logic and an immediately invoked function expression.

function LetsPlay()
{

    confirm("Request permission to play Abracadabra!") && (function () {
        prompt("Pick a number between 10 and 20");
        //more actions to follow
    })();
}

If the confirm function returns false, it doesn't bother to evaluate the expression following && (short-circuit logic).

It's easier to read the program if you put the inner function by itself.

function LetsPlay()
{
    confirm("Request permission to play Abracadabra!") && StartPlay();
}

function StartPlay() {
    prompt("Pick a number between 10 and 20");
    //more actions to follow
}

Upvotes: 2

Related Questions