What is == and === in JavaScript?

Comparing values is one of the most common tasks in programming. Have you ever wondered how comparison works in JavaScript?

In javascript there are two ways to do comparisons: the equality operator (==) and the strict equality operator(===)

the equality operator (==)

The equality operator or loose equality == checks if both the operands are equal and return a boolean value. If the operands are of the same type it just checks if the values are equal.

If the operands are of different types then the equality operator ( a.k.a. loose equality) automatically converts one operand to the same type based on rules of type coercion. These rules of coercion can be tricky to understand and are unpredictable.

note on type coercion

As we saw in the case of the equality operator if operands are of different types then type coercion is done. There are rules by which type coercion happens:

  1. if one of the operands is a string and the other one is a number, the string operand is converted to a number. if the string cannot be converted to a number then its value will be NaN.

  2. if any one of the operands is Nan it will always return false.

  3. for string and boolean values, the string value will be converted to boolean

  4. if one of the operands is a boolean, it converts the boolean to number

  5. null and undefined will return true.

  6. null and null comparison return true, same with undefined and undefined

  7. Objects are first converted to primitive type and compared.

the strict equality operator (===)

the === operator is similar to the == operator with just one difference. The strict equality operator does no performs automation type conversion if the operands are of different types and directly returns false. If the operands are of the same type it directly compares the values.

Which operator should we use?

As you can see from the above examples, the === result is more predictable and is the preferred way. So strict equality should be the preferred way of comparison.

Further reading

equality operator

strict equality

equality comparison