Array to Primitive Coercion
You'll learn how arrays magically turn into strings when JavaScript needs a primitive value, and why adding arrays together produces surprising results.
How Arrays Become Strings
When JavaScript needs to convert an array to a primitive value (like in arithmetic or string operations), it typically goes through the ToPrimitive process. For arrays, this almost always results in calling the array's toString() method.
An array's toString() method joins all its elements with commas:
[1, 2, 3].toString(); // "1,2,3"
[5].toString(); // "5"
[].toString(); // "" (empty string!)
Why [1,2] + [3,4] Gives "1,23,4"
When you use the + operator with arrays, JavaScript:
- Converts the first array to a string:
[1,2]becomes"1,2" - Converts the second array to a string:
[3,4]becomes"3,4" - Concatenates them as strings:
"1,2" + "3,4"="1,23,4"
[1, 2] + [3, 4]; // "1,23,4"
[] + []; // "" (two empty strings)
[5] + [10]; // "510" (string concatenation, not 15!)
Think of it like this: arrays don't know how to "add" themselves together mathematically, so JavaScript converts them to the only thing it can add easily—strings.
Nested Arrays
Even nested arrays flatten during conversion:
[[1, 2], [3, 4]].toString(); // "1,2,3,4"
Key Takeaway: Arrays convert to strings via toString(), which joins elements with commas. When adding arrays with +, you're actually concatenating their string representations, not performing math.