Equality Operators
JavaScript has two equality/inequality operators: the strict and the abstract equality operators.
Abstract Equality
The operator looks similar to that used in languages like Java and C++:
console.log(2 == 2); console.log(1 == 2); console.log(3 != 2);
The problem is, when the operands are of different types, the abstract equality operator converts the types first!
console.log("2" == 2); console.log(1 == true); console.log(0 == false); console.log("" == false); console.log("0" == false); // both are converted to 0
Type conversion before checking for equality is more error prune than it can be desired.
Do not use the "abstract equality" operators
==
and!=
.
Strict Equality
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:
console.log(2 === 2); console.log(1 === 2); console.log(3 !== 2);
If the operands don't have the same type, then they are considered unequal:
console.log("2" === 2); console.log(1 === true); console.log(0 === false); console.log("" === false); console.log("0" === false);
While numbers, boolean values and strings compared by value, object/array references are strictly equal if they refer to the same object in memory:
const student = { name: "John Doe" }; const courseAssistant = { name: "John Doe" }; const headAssistant = courseAssistant; console.log(student === courseAssistant); // false console.log(headAssistant === courseAssistant); // true
A good read: Object equality in Javascript.
Nuances
Note that undefined
and null
are only equal to themselves (unless compared using abstract equality).
console.log(undefined === undefined); console.log(null === null); console.log(undefined === null); // false console.log(undefined == null); // true
Here is a bit of madness, NaN
is not equal to NaN
no matter what equality operator you use
console.log(NaN == NaN); console.log(NaN === NaN);
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:
let num = NaN; console.log(Number.isNaN(num)); console.log(Object.is(num, NaN));
Object.is
is a new addition to JavaScript which works similar to strict equality except for NaN
and +0
/-0
.
console.log(+0 === -0); console.log(Object.is(-0, +0));
JavaScript Object.is
is designed to have the properties of an equivalence relation (it is reflexive, symmetric, and trasitive).
Resources
- MDN Web Docs has a great article on JavaScripts "Equality comparisons and sameness" available at this link.