Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it illegal to have var inside an if() expression in javascript?

Tags:

javascript

At least in V8 something like

if((var i = x*x) == 2){}

will give an error about an unexpected 'var' keyword. However there is no error if the var happens before the if() but I still leave the assignment of i in the expression. Why such an odd exception? Is this in the ECMA script standard somewhere? Is there a undetectable closure happening within the evaluation of the if() expression so leaving in the var would make my assignment disappear?

To further generalize it appears that var must have no non-white space characters preceding it.

like image 548
Steven Noble Avatar asked Apr 24 '11 05:04

Steven Noble


1 Answers

The short answer to your question is that you can't use a variable statement as the expression to evaluate in an if.

A more detailed answer is that according to ECMA-262 s12.5, an if statement has the form:

if ( Expression) Statement else Statement

ECMA-262 s11 describes an Expression as:

PrimaryExpression :
  this
  Identifier
  Literal
  ArrayLiteral
  ObjectLiteral
  ( Expression )

An expression that starts with var is a VariableStatment (ECMA-262 s12.2), which is not one of the above.

like image 123
RobG Avatar answered Oct 18 '22 07:10

RobG