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?
JavaScript always evaluates expressions in strictly left-to-right order. In the expression w=x+y*z , for example, the subexpression w is evaluated first, followed by x , y , and z . Then the values of y and z are multiplied, added to the value of x , and assigned to the variable or property specified by expression w .
Conditional statements control behavior in JavaScript and determine whether or not pieces of code can run. There are multiple different types of conditionals in JavaScript including: “If” statements: where if a condition is true it is used to specify execution for a block of code.
Can I assume
myVar == "test"
will never be executed ifmyVar
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.
Yes, it is OK.
In javascript, the precedence is as below:
typeof
> !=/==
> &&
For a && b
, b
will never be executed when a
is false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With