It doesn't:
console.log(new Array(4).join(""+10) + " Batman!")
However, this does:
console.log(new Array(5).join("a"-10) + " Batman!")
Your code didn't work because of two reasons:
- Addition with a string and a number gets interpreted as string concatenation, so
""+10
becomes the string "10"
. You have to use subtraction.
- Even so, changing to subtraction isn't enough because the empty string
""
converts to the number 0
and results in 0-10
which is the number -10
which finally gets converted to the string "-10"
by join()
. You have to put something into the quotes that is not a valid number.
The reason it behaves this way, is that JavaScript sees the subtraction and tries to convert the string "a"
into a number, but it's not a valid number so it returns NaN
(meaning "not a number"). It then tries to subtract 10 from it, which also returns NaN
. The result is that you're calling new Array(5).join('NaN')
, which joins 5 empty array elements with the string "NaN" => NaNNaNNaNNaN
and then concatenating the string " Batman!"
to it.