Comparing an Array and a String Using == in JavaScript – Asked in an HCL Tech Interview.


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

const x = [1, 2];
const y = '1,2'; console.log(x == y);

Here:

  • x is an array containing two elements: [1, 2]
  • y is a string"1,2"

    The key operation in this code is:

    x == y

    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?

    x.toString(); // "1,2"

    The toString() method for an array joins its elements with a comma (","), producing:

    "1,2"

    Step 3: Evaluating the Comparison

    Now, our expression:

    x == y

    becomes:

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

    Since both values are now strings and they are exactly the same, the comparison evaluates to:

    true

    Step 4: Logging the Output

    console.log(x == y);

    Console Output:

    true

    🔍 Key Takeaways

    1. Array to String Conversion: When an array is compared to a string, JavaScript first converts the array to a string using its toString() method.
    2. Type Coercion in ==: The loose equality operator (==) allows implicit type conversion, leading to unexpected results if not understood properly.
    3. 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.

    Post a Comment

    Previous Post Next Post