Jamie Hutber
Jamie Hutber

Reputation: 28076

Node if statement execution order

I am confused why this if statement will throw a JS error. Why isn't the function running as soon as it returns true?

res.locals.user = null;
console.info(res.locals.user === null); //true
if (res.locals.user === null && res.locals.user.level > 5) {

Upvotes: 0

Views: 125

Answers (2)

jfriend00
jfriend00

Reputation: 707356

The && in your if statement is analogous to this:

res.locals.user = null;
console.info(res.locals.user === null); //true
if (res.locals.user === null) {
   // at this point you know that res.locals.user is null
   if (res.locals.user.level > 5) {
       // won't get here because res.locals.user.level will throw an exception
   } 
}

If the first part of an && comparison evaluates to truthy, then the second part will also be evaluated since for the whole statement to be true, both pieces of the statement must be truthy.


It appears that you may want this instead:

res.locals.user = null;
console.info(res.locals.user === null); //true
if (res.locals.user === null || res.locals.user.level > 5) {
    // will get here because only the first term will be evaluated
    // since when the first term evaluates to true, the || is already satisfied
}

Or since I'm not quite sure which logic you want, maybe you wanted this:

res.locals.user = null;
console.info(res.locals.user === null); //true
if (res.locals.user !== null && res.locals.user.level > 5) {
    // will not get here because res.locals.user doesn't pass the first test
    // won't throw an exception because 2nd term won't be evaluated
}

Upvotes: 3

Robert Moskal
Robert Moskal

Reputation: 22553

Because the first part of the evaluation is true, so it goes on to evaluate the next part which will then always throw an exception as the first part was true. It's like a paradox :)

There are languages where the the && only executes the second comparison if the first is true (like java). However, what you wrote would fail in any language. You can't be null and level>5 all at once.

Upvotes: 1

Related Questions