Understanding the Code Step by Step
The given JavaScript snippet involves a comparison (==
) between an array (x
) and a string (y
). Let’s break it down carefully to understand the output.
Step 1: Understanding the Given Code
Here:
x
is an array containing two elements:[1, 2]
y
is a string:"1,2"
The key operation in this code is:
This involves type coercion because the ==
(loose equality) operator performs implicit conversions when comparing different data types.
Step 2: How Does JavaScript Handle ==
Between an Array and a String?
In JavaScript, when an array is compared with a string using ==
, the array is first converted into a primitive value (typically a string) before the comparison.
👉 Rule: When an array is used in a non-numeric context, JavaScript automatically calls its .toString()
method.
How x
(the array) is converted to a string?
The toString()
method for an array joins its elements with a comma (","
), producing:
Step 3: Evaluating the Comparison
Now, our expression:
becomes:
Since both values are now strings and they are exactly the same, the comparison evaluates to:
Step 4: Logging the Output
Console Output:
🔍 Key Takeaways
- Array to String Conversion: When an array is compared to a string, JavaScript first converts the array to a string using its
toString()
method. - Type Coercion in
==
: The loose equality operator (==
) allows implicit type conversion, leading to unexpected results if not understood properly. - Best Practice: To avoid unexpected type coercion, always use strict equality (
===
), which does not perform implicit conversions.
✔ Final Answer:
A) true
🔹 This question appeared in the HCL Tech 2nd round of interview, testing the candidate’s knowledge of type coercion and the comparison (==) operator in JavaScript.