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
Here:
x
is an array containing a single element[1]
.y
is an array containing a single element[2]
.
The key operation is:
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:
- Convert arrays to strings using
.toString()
- 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
Step 2.2: Concatenating the Strings
Now the expression:
is evaluated as:
Since one operand is a string, JavaScript treats the +
operator as string concatenation, producing:
Step 3: Logging the Output
Console Output
Remember key points:
- Arrays are objects in JavaScript, and the
+
operator does not perform numeric addition on arrays. - JavaScript first converts arrays to strings using
.toString()
, which joins elements with commas (,
) by default. - Example : [1,2] → "1,2"
- 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.