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