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