whatstheoutput_

#61: Number() on arrays

Topic: coercion · Difficulty: ★★★

console.log(Number(['5']));
console.log(Number([1, 2]));
console.log(Number([]));

Output

5
NaN
0

Why

Number() converts its argument to a primitive first, and for arrays that means calling toString(), which joins the elements with commas. A single-element array like ['5'] stringifies to just '5' (no commas needed), and Number('5') successfully parses that as the number 5. A multi-element array like [1, 2] stringifies to '1,2', which Number() cannot parse as a valid numeric literal at all, so the result is NaN. An empty array stringifies to the empty string '', and Number('') is specified to be 0, not NaN, because an empty string is treated as 'no digits, default to zero'. All three cases go through the exact same string-conversion path but land on very different results depending purely on the array's length.

More coercion puzzles

Play today's puzzle →