ey dee ey em
ey dee ey em

Reputation: 8603

meaning of pattern return var && var ==='something' in javascript

in a function, I saw return myVar && anotherVar === 'error';

Does this statement return a true / false depends on whether the && statement evaluate to be true or false after evaluating both conditions? so if let's say both a and b are true, the return result should be true, right? I thought so, but when I test it out in chrome console, I got error of Uncaught SyntaxError: Illegal return statement when I do var a = 'abc', b = '123'; then return a && b;

Any thoughts?

Upvotes: 2

Views: 670

Answers (2)

Joel Coehoorn
Joel Coehoorn

Reputation: 415820

Is does not necessarily evaluate both conditions. Logical operators in javascript use something called short-circuit evaluation so that the system only runs the first condition if it can determine the result based on the first condition alone. The code is equivalent to this:

if (myVar)
{
    //if the first condition fails we never enter the block
    // and never check this condition
    if (anotherVar === 'error')
    {
       return true;
    }  
}
return false;

This is a common pattern that is pretty easy to understand once you've seen it a few times, and therefore it's almost always preferable to use the shorter form you encountered for the question over writing out the whole mess from this answer.

For your test, rather than calling return, just debug.print or debug.log the result.

Upvotes: 3

taxicala
taxicala

Reputation: 21759

You are getting that error because you are not using return inside a function, try the following in any console:

function foo() {
    var a = "abc", b = "123";
    return a && b;
};
foo();

As per the && question, thats a logical AND operator, if the first (a) in this case, is false, the second won't be evaluated.

Upvotes: 2

Related Questions