Multiple conditions in an if statement: Need for validating undefined before checking other conditions [duplicate]

StackOverflow https://stackoverflow.com/questions/13557551

Frage

Possible Duplicate:
Javascript conditional order evaluation

How do multiple conditions in an if-statement pan out?

if( bacon && bacon == "crispy") {
   self.eat(bacon);
}

If bacon doesn't exist, will it still try to check if bacon is "crispy"?

War es hilfreich?

Lösung

No, it uses short-circuit evaluation, so if evaluating the LHS means it doesn't need to evaluate the RHS, it won't.

This is exploited in JavaScript quite frequently...

foo = foo || "bar";

If foo is truthy (the LHS), then the condition is known to be true and foo will be assigned its value (these conditions return the last evaluated expression).

However, if foo is falsy, it will evaluate the RHS expression, and then assign that result to foo.

Andere Tipps

The && operator is a short-circuit operator in JavaScript that will prevent the rest of the statement from being evaluated if the first condition is false.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top