DEV Community

Cover image for JavaScript == vs ===: The Truth Behind the Equality Operators
Mubashir Hassan
Mubashir Hassan

Posted on

JavaScript == vs ===: The Truth Behind the Equality Operators

Whether you're a beginner or writing production-grade JavaScript, you've definitely seen == and === being used — sometimes even interchangeably. But should they be? Let’s explore what they really do, how they differ, and why one is generally safer than the other.

The Loose Equality Operator: ==

The == operator compares values after performing type coercion. This means JavaScript will automatically convert one or both values to a common type before comparing them.

'5' == 5         // true  → string '5' is coerced to number 5
0 == false       // true  → false becomes 0
null == undefined // true → special rule
[] == ''         // true  → both become '' (empty string)
Enter fullscreen mode Exit fullscreen mode

This behavior may seem helpful at first, but it leads to unexpected results and bugs — especially when working with user input or API responses.
**
The Strict Equality Operator: ===**

The === operator, also known as strict equality, compares both value and data type. No coercion happens. If the types are not the same, the result is false — simple and predictable.

'5' === 5        // false → string vs number
0 === false      // false → number vs boolean
null === undefined // false → different types
[] === ''        // false → array vs string
5 === 5          // true  → same value and type
Enter fullscreen mode Exit fullscreen mode

Why You Should Prefer === Over ==

Using == can introduce silent bugs due to type coercion. Consider this:

if ('0' == false) {
  console.log("They're equal!");
}
Enter fullscreen mode Exit fullscreen mode

This logs "They're equal!" because:

'0' becomes 0

false becomes 0

0 == 0 → true

This kind of implicit behavior can be hard to debug

*When == Does Make Sense
*

There are very few scenarios where == is justifiable:

if (value == null) {
  // matches both null and undefined
}
Enter fullscreen mode Exit fullscreen mode

This is a common pattern to check for null or undefined in a single condition. Other than that, stick to ===.

Top comments (0)