The Difference Between == and === in JavaScript

Image by Annie Spratt.

In JavaScript, there are two types of equality operators used to compare values: == and ===. Whilst both operators are used to compare values, there is a significant difference between the way the two of them behave and the results they return. You would be surprised how often even wellversed developers can be tripped up by these, so I thought I'd write an article to discuss the differences between the two operators, and when to use each of them.


Abstract equality operator (==)

The == operator, also known as the "abstract equality operator", follows JavaScript's Abstract Equality Comparison algorithm. Depending on the operand types, it may perform type coercion on one operand before comparison; it does not simply convert both values to one common type.

For example:

console.log(1 == '1');  //=> trueconsole.log(true == 1);  //=> trueconsole.log(null == undefined);  //=> true

The rules are specific to the operand types rather than one general conversion to a shared type.

In the first example, JavaScript converts the string '1' to the number 1. In the second, it converts true to the number 1. null and undefined are equal to each other through a specific rule in the algorithm, not because both are generally converted to a shared type.


Strict equality operator (===)

On the other hand, the === operator, also known as the "strict equality operator," compares two values without type coercion. If the operands are of different types, the comparison will return false.

For example:

console.log(1 === '1');  //=> falseconsole.log(true === 1);  //=> falseconsole.log(null === undefined);  //=> false

As you can see from these examples, the === operator does not convert the operands to the same type before comparison.

In the first example, the comparison returns false because the number 1 is not equal to the string '1'. In the second example, the comparison returns false because the boolean value true is not equal to the number 1. And in the third example, the comparison returns false because null and undefined are not the same type.


The Wrap‑Up

In most cases, it is recommended that you use the === strict operator for equality comparisons, as it avoids unexpected behaviour due to type coercion. However, there may be cases where type coercion is desired, in which case the == operator can of course be used.

console.log(1 == '1');  //=> trueconsole.log(1 === '1');  //=> falseconsole.log(true == 1);  //=> trueconsole.log(true === 1);  //=> falseconsole.log(null == undefined);  //=> trueconsole.log(null === undefined);  //=> false

In conclusion, the main difference between the == and === operators is that == may perform typespecific coercion before comparison, whilst === does not, and is stricter as a result.


Looking for technical direction?

I support teams that need senior judgement on React, Next.js, headless CMS architecture, performance, migrations, and technical SEO.