When you assign something the value returned isn't representative of whether or not the assignment was successful, it actually just returns the right hand side of the assignment (e.g, the test = 2
in if (test = 2)
would return 2
which is "truthy" in JavaScript, thus causing console.log(test)
to evaluate. This can actually be quite useful in certain cases. For example:
while ((value = retrieveSomeValue()) !== null) {
console.log(value);
}
The code above continually assigns some variable value
to the result of some function retrieveSomeValue
, tests the resulting value to make sure it isn't null, and executes the while body.
To answer your question though: The ===
operator is more easily distinguished from the =
operator and probably behaves more like what you would expect out of ==
. Which equals operator (== vs ===) should be used in JavaScript comparisons?