Order of evaluation in if statement in Javascript
javascript
Solution
Can I assume `myVar == "test"` will never be executed if `myVar` is undefined?
Yes. The expression you are testing is a logical AND expression and the order of evaluation of the two operands is specified:
The production LogicalANDExpression `:` LogicalANDExpression `&&` BitwiseORExpression is evaluated as follows (emphasis added):
- Let lref be the result of evaluating LogicalANDExpression.
- Let lval be GetValue(lref).
- If ToBoolean(lval) is false, return lval.
- Let rref be the result of evaluating BitwiseORExpression.
- Return GetValue(rref).
That basically says evaluate the first operand, if the result of that evaluation is `false`, the entire expression is `false`, and the second operand is never evaluated.
Problem
In order to protect my code from accessing undeclared variables I use ``` if (typeof myVar != 'undefined') ``` This works fine but I'd like to stick another if statement in it. Something like converting this: ``` if (typeof myVar != 'undefined'){ if (myVar == "test"){} } ``` to this: ``` if (typeof myVar != 'undefined' && myVar == "test") ``` Considering `myVar` may be undefined, is this last code secure in every case of usage and every browser? Is it possible that various statements inside an `if ()` are not evaluated in the order they're written? Can I assume `myVar == "test"` will never be executed if `myVar` is undefined?