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 work but I just found out that it does.
From the ES5.1 specification (12.5)
Any valid expression can be placed inside an if.
foo = trueis an expression and it evaluates to true.To avoid bugs like writing
=instead of==in the future write it likeWhich will throw a assignment error since you can’t assign values to literal values like
true