let foo;
foo = 1 === 1;
if ((foo = -5)) {
console.log("Will always work");
} else {
console.log("Will NEVER work");
}
I understand that the variable foo
is set to be 1 === 1
, so it is true. Then there is a condition in the second line.
How the condition is fulfilled so I get the first console.log
printing? Why doesn’t it skip to the second printing? Is foo = -5
also true?
2
Answers
Yes,
foo = -5
is true because the assignment operator evaluates to -5 which is not zero.let
statement lets you reassign variables so you assigned1
to the variable then byif (foo = -5)
, you reassign the value-5
to the variable, so the condition will always be true.Assignment is not the same as comparison.
=
is assignment, but==
and===
are comparison.You should use
if (foo === -5)
if you want the variable’s value to be1
, thereforeif (foo === -5)
will be false, and it’ll skip toelse
aka the second part ofconsole.log
.See: Expressions and operators to learn more about assignment and comparison.