简体   繁体   中英

Why is it illegal to have var inside an if() expression in 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM