You can check strict equality in JavaScript using the operator ===
.
This operator does strict comparison and considers the operands equal if they’re of the same type,
and their values are equal.
console.log(1 === 1); // true
console.log(1 === '1'); // false
console.log(1 === true); // false
There one particular corner case with the strict equality operator in JS.
It’s related to NaN
.
NaN
is a special numeric value that’s not equal to itself.
console.log(NaN === NaN) // false
NaN
appears when JavaScript can’t make sense
of the provided arithmetic expression and can’t calculate it.
For example, you can try to subtract a string from a number and get NaN
.
const x = 10 - 's';
console.log(x); // NaN
console.log(typeof x); // number
console.log(typeof NaN); // number
console.log(x === NaN); // false
To fix the issue, you can use the function Object.is
to check if the numbers are equal.
Contrary to the strict equality operator ===
, the Object.is
method returns true even if both numbers are NaN
.
const x = 5;
const y = NaN;
console.log(Object.is(x, 5)); // true
console.log(Object.is(y, NaN)); // true