What happens when you add two arrays in JavaScript? – Asked in a Deloitte Interview


Our Javascript Code:

console.log([1,2,3] + [1,3,4]);

Step-by-Step Breakdown

Step 1: What does the + operator do?

In JavaScript:

  • If both operands are numbers, it adds them.
  • If either operand is a string, it concatenates them.
  • If the operands are arrays, JavaScript tries to convert them to strings before applying +.

So now we ask:


Step 2: How does JavaScript convert arrays to strings?

JavaScript uses the toString() method internally when it needs a string version of an array.

[1, 2, 3].toString(); // "1,2,3"
[1, 3, 4].toString(); // "1,3,4"

So in your code:

[1,2,3] + [1,3,4]

        ↓
"1,2,3" + "1,3,4"
        ↓
   "1,2,31,3,4"

That’s just plain string concatenation, not mathematical addition or array merging!


✔ Final Answer:

A) 1,2,31,3,4

This question appeared in the Deloitte 2nd round of interview, testing the candidate’s knowledge of type coercion of array when you use plus (+) operator to add to array in JavaScript.


Remember key points

  • JavaScript does not add arrays with +.
  • Instead, it converts arrays to strings and concatenates them.
  • If you see weird results like "1,2,31,3,4", check if you’re accidentally using + with arrays!

Post a Comment

Previous Post Next Post