Why is the following not valid JavaScript?
if (var foo = (true || false)) {
console.log(foo);
}
When you declare a variable in JavaScript the assignment will return the value of the new variable, so you can do something like this:
if (foo = (true||false)) console.log('Hello!');
> Hello!
Now if you call foo it will have a value of true:
console.log(foo);
> true
You cannot use the var private word, because if is a statement, not a function. If you want to be sure about the scope of your variable, then you have to declare it first:
var foo;
if (foo = (true||false)) console.log('Hello!');
> Hello!
Take a look here:
http://www.ecma-international.org/ecma-262/5.1/#sec-12.5
then here:
http://www.ecma-international.org/ecma-262/5.1/#sec-11
And conclude that the syntax isn't valid because of:
http://www.ecma-international.org/ecma-262/5.1/#sec-12.2
in relation (or rather lack thereof) to the above.
trueto the console.(true||false)evaluates to true. The assignment offooevaluates to true. Theifchecks the conditional which is the result of the assignment, whcih istrue. The body of the if "should" then run. Clearly it is not valid JS, but my question is why?if (foo = true)would return true. it is just that thevarkeyword can not be used in a comparison. it's a statement, not a function.