Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of evaluation in if statement in Javascript

Tags:

javascript

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?

like image 719
Saturnix Avatar asked Aug 29 '13 09:08

Saturnix


People also ask

Does JavaScript evaluate left to right?

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 .

CAN YOU DO IF statements in JavaScript?

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.


2 Answers

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.

like image 62
James Allardice Avatar answered Sep 18 '22 15:09

James Allardice


Yes, it is OK.

In javascript, the precedence is as below:

typeof > !=/== > &&

For a && b, b will never be executed when a is false.

like image 26
xdazz Avatar answered Sep 18 '22 15:09

xdazz