Array Coercion Behavior
You'll learn how JavaScript converts arrays to strings and numbers, often producing surprising results in operations.
How Arrays Convert to Primitives
When JavaScript needs to coerce an array to a primitive value, it typically converts the array to a string first. Arrays use their join(',') method during this conversion — meaning the array elements are joined together with commas (without square brackets).
This happens through the ToString abstract operation you learned earlier:
String([1, 2, 3]) // "1,2,3"
String([]) // "" (empty string!)
String([42]) // "42"
Surprising Results in Arithmetic
When arrays appear in arithmetic operations, they convert to strings first, then those strings may convert to numbers:
[1, 2] + [3, 4] // "1,23,4" (string concatenation)
[] + [] // "" (empty string)
[5] - 2 // 3 (number "5" minus 2)
[1, 2] - 1 // NaN ("1,2" can't convert to number)
What's happening?
[5]→"5"→5(numeric context works)[]→""→0(empty string coerces to 0)[1, 2]→"1,2"→NaN(comma prevents number conversion)
The Empty Array Exception
An empty array is particularly tricky:
[] + 5 // "5" (empty string + number)
[] - 5 // -5 (empty string becomes 0, then 0 - 5)
+[] // 0 (empty string coerces to 0)
Key Takeaway: Arrays coerce to strings via join(','), producing just their comma-separated elements. Single-element arrays become that element's string, empty arrays become empty strings (which then become 0 in numeric contexts), and multi-element arrays typically produce NaN in arithmetic.