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

In JavaScript, === (strict equality) is generally preferred over == (loose equality) because it checks both value and type without implicit type coercion. Below are detailed examples illustrating the differences:

1. Comparing Primitives

Example== Result=== ResultExplanation
"5" == 5truefalse"5" (string) is coerced to 5 (number).
"5" === 5falsefalseDifferent types.
0 == falsetruefalsefalse is coerced to 0 (number).
0 === falsefalsefalseDifferent types (number vs boolean).
"0" == falsetruefalseBoth coerced to 0 (string "0"0, false0).
null == undefinedtruefalseSpecial case: null and undefined are only loosely equal.
NaN == NaNfalsefalseNaN is not equal to itself in JavaScript. Use Object.is(NaN, NaN) instead.

2. Comparing Objects/Arrays

Example== Result=== ResultExplanation
[] == ""truefalseEmpty array [] is coerced to "" (string).
[] === ""falsefalseDifferent types (object vs string).
{} == "[object Object]"truefalseObject coerced to "[object Object]" (string).
{} === {}falsefalseDifferent object instances (reference comparison).

3. Edge Cases

Example== Result=== ResultExplanation
"true" == truefalsefalse"true"NaN (number), true1 (number). NaN != 1.
"1" == truetruefalse"1"1, true1.
"\n" == 0truefalse"\n" (string) → 0 (number).
" " == 0truefalseEmpty/whitespace strings coerce to 0.

When to Use == (Rare Cases)

  1. Check for null or undefined:
   if (value == null) { ... } // true if value is `null` or `undefined`
  1. Intentional Type Coercion (e.g., user input as strings vs numbers):
   const userInput = "10";
   if (userInput == 10) { ... } // true

Best Practices

  • Default to === for predictable and safe comparisons.
  • Avoid == unless you explicitly want type coercion and understand the rules.
  • Use Object.is for edge cases like NaN checks:
  Object.is(NaN, NaN); // true

Summary

ScenarioUse
Most comparisons===
Checking null/undefinedvalue == null
Intentional type coercion== (cautiously)

By using ===, you avoid subtle bugs caused by unexpected type coercion.

Leave a Reply

Your email address will not be published. Required fields are marked *