Our Javascript Code:
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.
So in your code:
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!