Last updated: Mar 2, 2024
Reading timeยท2 min
Use the strict inequality (!==) operator to check if two strings are not
equal, e.g. a !== b
.
The strict inequality operator returns true
if the strings are not equal and
false
otherwise.
const a = 'one'; const b = 'two'; if (a !== b) { // ๐๏ธ this runs console.log('โ strings are NOT equal'); } else { console.log('โ๏ธ strings are equal'); }
We used the strict inequality (!==) operator to check if two strings are not equal.
The operator returns a boolean result:
true
if the values are not equalfalse
if the values are equalThe strict inequality (!==) operator is the negation of the strict equality (===) operator.
Here are some more examples of using the strict inequality (!==) operator.
console.log(5 !== '5'); // ๐๏ธ true console.log('one' !== 'one'); // ๐๏ธ false console.log('one' !== 'ONE'); // ๐๏ธ true console.log('' !== ' '); // ๐๏ธ true console.log(5 !== 5); // ๐๏ธ false console.log(5 !== 10); // ๐๏ธ true console.log(true !== true); // ๐๏ธ false console.log(true !== false); // ๐๏ธ true console.log([] !== []); // ๐๏ธ true console.log({} !== {}); // ๐๏ธ true console.log(null !== null); // ๐๏ธ false console.log(undefined !== undefined); // ๐๏ธ false console.log(NaN !== NaN); // ๐๏ธ true
Two values of different types will never be equal when using the strict inequality operator.
The strict operators (!==, ===) produce more predictable results.
Notice that in the last example, NaN !== NaN
returns true
. This is because
NaN
(not a number) is the only value in JavaScript that is not equal to
itself.
One common use case for the loose equality (==) and loose inequality (!=) operators is when checking if a value is nullish.
const a = null; if (a == null) { // ๐๏ธ this runs console.log('a is null or undefined'); } else { console.log('a is not null and undefined'); } if (a != null) { console.log('a is not null and undefined'); }
The loose equality operator (==) considers null
and undefined
to be equal
which is not the case when using the strict equality operator (===).
console.log(null == undefined); // ๐๏ธ true console.log(null === undefined); // ๐๏ธ false
This is why the condition if (a != null)
evaluates to true
if a
is not
equal to null
and undefined
.
This is the most common use case for the loose equality (==, !==) operators in JavaScript.
If you use the loose equality operator to check if two values are not equal, you might get confusing results.
If you want to read more about how the loose equality operators work, check out this section of the MDN docs.