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

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

Вопрос

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"?

Это было полезно?

Решение

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.

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top