Why Empty Arrays Equal Zero But Not Each Other, Double Equals Confusion and Loose Equality in JavaScript: Why These Arrays Don’t Behave as Expected.

Why Empty Arrays Equal Zero But Not Each Other Double Equals Confusion and Loose Equality in JavaScript Why These Arrays Do not Behave as Expected

Our code :-

console.log([] == 0);
console.log([0] == [0]);

🔹 Line 1: [] == 0

Step-by-step:

  1. Operands:
    • Left: [] → an empty array (object).
    • Right: 0 → a number.
  2. Loose equality == allows type coercion, so JavaScript tries to make the types match.
  3. [] is an object. When comparing an object to a primitive, JavaScript first converts the object to a primitive using ToPrimitive.
  4. So:
    • []"" (an empty string)
    • (because .toString() on an empty array returns "")
  5. Now the expression becomes:

    • "" == 0
  6. Next, JavaScript converts both sides to numbers:

    • ""0
    • 0 stays 0
  7. Now it’s:

    • 0 == 0 // true

Result: true


🔹 Line 2: [0] == [0]

Step-by-step:

  1. Both sides are arrays, each containing a single element: 0.
  2. Arrays are objects in JavaScript, and objects are compared by reference, not by value.
  3. [0] == [0] is comparing:

    • Two different array instances (in memory), even though they contain the same value.
  4. Since they’re not the same object in memory:

    • false

Result: false


✔ Final Answer:

A) true false

This question appeared in the Tech Mahindra 2nd round of interview, testing the candidate’s knowledge of comparisons operator between arrays in JavaScript.

Post a Comment

Previous Post Next Post