What Happens When You Compare an Array and a String with == in JavaScript? – Asked in an IBM Interview


 Step-by-Step Breakdown

Step 1: Understand the == Operator

  • The == operator is called the loose equality operator.
  • It does not check types strictly. Instead, it tries to coerce the values to the same type before comparing them.

So when we do:

    arr1 == str

JavaScript will try to convert one side to match the other (usually converting the object to a primitive like a string).


Step 2: What Happens When an Array is Compared to a String?

JavaScript internally performs the following steps:

  1. arr1 is an object (array is a kind of object).
  2. The comparison triggers type coercion, because we're comparing an object with a string.
  3. JavaScript tries to convert the array to a string using .toString().

        arr1.toString(); // "1,2,3"

So, under the hood, the comparison becomes:

    "1,2,3" == "1,2,3"

Now both sides are strings → and they are equal.


Step 3: The Final Comparison

"1,2,3" == "1,2,3"true

✔ Final Answer:

A) true

This question appeared in the IBM 2nd round of interview, testing the candidate’s knowledge of array and string coerce and the loose equality operator in JavaScript.

Post a Comment

Previous Post Next Post