I thought if statements weren't supposed to contain assignment operators but rather the comparison operators (==, ===) but this works perfectly. Why?
var foo = true,
bar = true;
if (foo = true) {
console.log('foo is true');
}
I was taught that this wouldn't wo开发者_开发知识库rk but I just found out that it does.
What you're actually doing, is still comparing:
if ((foo = true) == true) ...
This is an 'abbreviation' for:
foo = true;
if (foo == true) ...
So it does make sense =)!
From the ES5.1 specification (12.5)
IfStatement :
if ( Expression ) Statement else Statement
if ( Expression ) Statement
Any valid expression can be placed inside an if.
foo = true
is an expression and it evaluates to true.
To avoid bugs like writing =
instead of ==
in the future write it like
if (true = foo) {
}
Which will throw a assignment error since you can't assign values to literal values like true
The assignment is evaluated to true
, beacuse JavaScript returns the value that it sets the variable to.
var foo = true,
bar = true;
if (foo = true) {
console.log('foo is true');
}
becomes:
var foo = true,
bar = true;
if (true) {
console.log('foo is true');
}
which passes the if
. Note that setting to false
would not work, because the conditional would evaluate to false
which does not pass the if
.
Specification about if
:
if ( Expression ) Statement
You are using the assignment expression:
AssignmentExpression : ConditionalExpression LeftHandSideExpression AssignmentOperator AssignmentExpression
The =
is specified as:
Simple Assignment ( = )
The production AssignmentExpression : LeftHandSideExpression = AssignmentExpression is evaluated as follows:
...
2 . Let rref be the result of evaluating AssignmentExpression.
3 . Let rval be GetValue(rref).
...
6. Return rval.
Tragically, you are in fact assigning foo to true. :)
精彩评论