== operator and the
=== operator, also known as abstract equality comparison and strict equality comparison.
Strict Equality With
Given 2 values
x === y:
- Check the types of
y. If they are different types, return
yare numbers, first check if either
NaN, and return
falseif one is
NaN. If both
true. Otherwise, check to see if they are the same number.
yare both booleans, both strings, or both symbols, compare them by value.
yare both objects, return true if and only if they reference the same object.
In short, here are the important details of
- No implicit type coercions.
valueOf()or do anything else to try to convert objects to primitives.
- No value is
=== NaN. You should not use
===to check for
- Object comparison is by reference – two different objects can contain the exact same keys, but
===will still say they’re different.
Abstract Equality With
== operator uses a more complex abstract equality comparison algorithm to compare whether
y are equal. Here’s a brief overview:
yare the same type, check if
x === y.
yare both either
xis a number and
yis a string, convert
yto a number and then compare using
===. Similarly, if
xis a boolean or string, and
yis a number, convert
xto a number.
yis a boolean, convert the other value of a number and compare them.
xis an object and
yis a symbol, string, or number, try to convert
xto a primitive using
valueOf()and then compare using
In general, you should always use
=== rather than
== unless you’re sure you know what you’re doing. There is one neat functional use for
==: checking for
undefined (so-called nullish values) with a single check:
v == null is a more concise way of checking if
v is strictly equal to