JavaScript has two equality/inequality operators: the strict and the abstract equality operators.
The operator looks similar to that used in languages like Java and C++:
The problem is, when the operands are of different types, the abstract equality operator converts the types first!
Type conversion before checking for equality is more error prune than it can be desired.
Do not use the “abstract equality” operators ==
and !=
.
The strict equality uses an extra equal sign. It performs the equality comparison in a more exact identity sort of matching.
When the operands have the same type, their value is compared:
If the operands don’t have the same type, then they are considered unequal:
While numbers, boolean values and strings compared by value, object/array references are strictly equal if they refer to the same object in memory:
A good read: Object equality in Javascript.
Note that undefined
and null
are only equal to themselves (unless compared using abstract equality).
Here is a bit of madness, NaN
is not equal to NaN
no matter what equality operator you use
So JavaScript’s equality operator is not an equivalence relation (since it is not reflexive).
If you want to check if a variable is NaN
, you should try one of the following static methods:
Object.is
is a new addition to JavaScript which works similar to strict equality except for NaN
and +0
/-0
.
JavaScript Object.is
is designed to have the properties of an equivalence relation (it is reflexive, symmetric, and transitive).
MDN Web Docs has a great article on JavaScripts “Equality comparisons and sameness” available at this link.