Skip to content

Difference between == and ===

JavaScript has two equality operators:

  • ===, strict equality, is true only when both values have the same type and the same value.
  • ==, loose equality, first converts the two values to a common type when their types differ, and then compares them.

Their opposites are !== and !=. Use === and !== by default, because the conversions that == makes are hard to predict.

const quantity = 5;
const typedIn = '5';
console.log(quantity == typedIn);
console.log(quantity === typedIn);
console.log(quantity === Number(typedIn));

This prints:

true
false
true

== converts the string '5' to the number 5 before comparing, so it reports a match. === sees a number and a string and reports no match. Where a value might be a string, such as the contents of a form field, convert it explicitly with Number() and then compare with ===, so the conversion is visible in the code.

The conversion rules make == give answers that do not fit together:

console.log(0 == '');
console.log(0 == '0');
console.log('' == '0');
console.log(false == '0');
console.log(null == undefined);
console.log(null == 0);
console.log(null === undefined);

This prints:

true
true
false
true
true
false
false

0 equals both '' and '0', yet '' and '0' do not equal each other, so == is not even consistent with itself. Type Casting, Converting and Coercion explains the rules behind these results.

The one common use of == is value == null, which is true for both null and undefined and for nothing else. It is a short way to test for “no value”, though value === null || value === undefined says the same thing more plainly.

For objects, which include arrays and functions, both operators ask whether the two sides are the same object, not whether they hold the same contents:

const bookA = { title: 'Middlemarch' };
const bookB = { title: 'Middlemarch' };
const sameBook = bookA;
console.log(bookA == bookB);
console.log(bookA === bookB);
console.log(bookA === sameBook);
console.log([1, 2] === [1, 2]);
console.log(bookA.title === bookB.title);

This prints:

false
false
true
false
true

bookA and bookB are two separate objects that happen to look alike, so they are not equal. sameBook is a second name for the object in bookA, so it is. To compare contents, compare the properties that matter, as the last line does. Pass by Reference explains why assigning an object does not copy it.

NaN, the number that means “not a number”, is not equal to anything, itself included:

const reading = NaN;
console.log(reading === NaN);
console.log(Number.isNaN(reading));
console.log(Object.is(reading, NaN));
console.log(0 === -0, Object.is(0, -0));

This prints:

false
true
true
true false

Test for NaN with Number.isNaN. Object.is is a third comparison that behaves like === except in these two edge cases: it treats NaN as equal to itself, and it tells 0 and -0 apart.

Steve Griffith covers this topic in his video Difference Between == and === in JavaScript.