comparison
===
==
operator
javascript

Which equals operator (== vs ===) should be used in JavaScript comparisons?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In JavaScript, the == and === operators are both used for comparisons, but they behave differently:

1. === (Strict Equality)

  • Type Comparison: === checks for both value and type equality. This means that the two values must be of the same type and have the same value to be considered equal.
  • No Type Coercion: The === operator does not perform type coercion. If the types of the two values being compared are different, the comparison will return false.

Example:

javascript
5 === 5;       // true
5 === '5';     // false (number vs. string)
'hello' === 'hello'; // true

2. == (Loose Equality)

  • Type Coercion: == checks for value equality, but it performs type coercion if the types of the two values are different. This means that it will try to convert one or both values to a common type before making the comparison.
  • Less Predictable: Because of type coercion, == can lead to unexpected results, making it less predictable.

Example:

javascript
15 == 5;       // true
25 == '5';     // true (string '5' is coerced to number 5)
30 == false;   // true (false is coerced to number 0)
4null == undefined; // true

Best Practice: Use ===

  • Predictability: Using === (strict equality) is generally considered best practice in JavaScript because it avoids unexpected results due to type coercion. It ensures that your comparisons are both type-safe and value-safe.
  • Clarity: It makes your code more explicit and easier to understand, as you are always certain that the comparison is checking both type and value.

When to Use ==

  • Legacy Code: In some cases, == might be used in legacy code or specific situations where type coercion is desired. However, this should be done with caution and understanding of the behavior.

Summary

  • Use ===: Preferred for most cases due to its strict equality check, avoiding type coercion.
  • Use ==: Only if you are intentionally taking advantage of type coercion and fully understand the implications.

By default, you should use === to make your code more robust and avoid the pitfalls of type coercion that can occur with ==.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.