Question

Does javascript skip statements if the outcome is already known? I'm asking this because for some reason my code doesn't console.log(b) when the outcome is alert('You Lose'). It does console.log when the outcome is alert('You Win').

C always equals true.

So when a = false it does not console.log(b), but when a = true it does console.log(b)

Why?

function example(c) {

var b = true;

    var a = validateFunction($('.div1'));    // returns true or false

    console.log(a);


    if (c === true) {  // c always equals true
        b = validateFunction($('.div2'));  // returns true or false
        console.log(b);
    }


    if (a === true && b === true) {
        alert('You Win');
    }
    else {
        alert('You Lose');
    }


}
Was it helpful?

Solution

It would seem to me that c is not === true. To verify, add an else clause to if (c === true) that contains something to the effect of console.log('C is not === true.');

OTHER TIPS

Yes, most languages parse if statements from left to right and stop as soon as they have a sure result.

Since your first expression in the if statement returns false, the whole statement can't return true, so it does not even try parsing it.

Same happens in an OR statement, if the first expression is false.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top