Avoid Comparison Surprises
Get in the habit of using the strict comparison operators (===
and !==
) in JavaScript. When you use ==
or !=
JavaScript will, depending on the values being compared, perform automatic type conversion, which can cause some odd and unexpected behavior.
Take this example:
'0' == 0; // Evaluates to true.
How is a string containing the character 0
equal to the integer zero? Because, when using ==
or !=
, JavaScript converts the string into a number before performing the comparison. Using the strict comparison operators works as expected:
'0' === 0; // Evaluates to false.
That’s just one example of how automatic type conversion can get you into an unexpected and hard-to-debug situation. Using ===
and !==
will avoid such nonsense and always do what you expect.