The == Operator in JavaScript

This post explains the JavaScript == operator, including type coercion rules and examples.

Apr 18, 2021 · 1 min read · 174 Words · -Views -Comments · Programming
JavaScript 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

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