What Happens When You Use the + Operator Between Two Arrays in JavaScript? – Asked in an IBM Interview


Understanding the Code Step by Step

The given JavaScript snippet involves array addition using the + operator, which is an interesting case because arrays in JavaScript are objects, and the + operator does not perform numerical addition when used with objects. Instead, it performs type coercion.


Step 1: Understanding the Given Code

const x = [1]; // Array with one element: [1]
const y = [2]; // Another array with one element: [2] console.log(x + y);

Here:

  • x is an array containing a single element [1].
  • y is an array containing a single element [2].

    The key operation is:

    x + y

    Since both x and y are arrays, JavaScript must determine how to handle addition (+) between two objects.


    Step 2: How Does JavaScript Handle x + y?

    🔹 Rule: When using + with objects, JavaScript converts them to primitive values.

    JavaScript follows these steps:

    1. Convert arrays to strings using .toString()
    2. Perform string concatenation (+) instead of numeric addition

      Step 2.1: Array to String Conversion

      Whenever JavaScript needs to convert an array to a primitive, it calls the .toString() method of the array.

      👉 Calling .toString() on x and y

      console.log([1].toString()); // "1"
      console.log([2].toString()); // "2"

        Step 2.2: Concatenating the Strings

        Now the expression:

        x + y

        is evaluated as:

        "1" + "2"

        Since one operand is a string, JavaScript treats the + operator as string concatenation, producing:

        "12"

        Step 3: Logging the Output

        console.log(x + y);

        Console Output

        "12"

        Remember key points:

        1. Arrays are objects in JavaScript, and the + operator does not perform numeric addition on arrays.
        2. JavaScript first converts arrays to strings using .toString(), which joins elements with commas (,) by default.
          1. Example : [1,2] → "1,2"
        3. Since the resulting values are strings, + performs string concatenation, not arithmetic addition.


          ✔ Final Answer:

          D) 12

          This question appeared in the IBM interview, testing the candidate’s knowledge of type coercion and the concatenation (+) operator in JavaScript.

          Post a Comment

          Previous Post Next Post