== and !=
The ==
and !=
operators do type coercion before comparing. This is bad because
it causes ' \f\r \n\t ' == 0
to be true
. This can mask type errors.
When comparing to any of the following values, always use the ===
or !==
operators, which do not do type coercion:
0 '' undefined null false true
If you want the type coercion, then use the short form. Instead of:
(foo != 0)
just say:
(foo)
And instead of:
(foo == 0)
say:
(!foo)
Use of the ===
and !==
operators is always preferred. There is a "Disallow ==
and !=
"
(eqeqeq
) option, which requires the use of
===
and !==
in all cases.
Get JavaScript: The Good Parts now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.