The == Operator in JavaScript

Apr 18, 2021 · 1 min read · 174 Words · -Views -Comments

I recently saw a question: how do you declare a so that a == 1 && a == 2 && a == 3 returns true? You can tell a must be an object, but what method should it use? This exposed how weak my understanding was of type coercion with ==, so I reviewed it.

Implicit type coercion with ==

If types differ, consider primitive and object types:

  • Primitive types
    • Number and string: string is converted to number
    • Number and boolean: boolean is converted to number
  • Object types
    • If one is an object, it calls valueOf and toString to convert to a primitive

If you use === (strict equality), there is no type conversion.

The question

(a ==1 && a== 2 && a==3)===true

Once you understand the rules, the solution is straightforward.

const a = {
  i: 1,
  valueOf: function () {
    return a.i++;
  }
};

Summary

  • This question tests implicit type coercion and is quite interesting.
  • In real projects, we usually use strict equality === and enforce it with ESLint to avoid surprises.
Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover