If I enter the following code into the JavaScript console, it returns the number 1310, but why?
console.log(131+"".split(',').map(Number));
I’m adding ""
to 131
to convert it to a string, then using the split
function to convert that string into an array, and the map
function to make sure the values in the array are Number
s.
I’m not sure where the 0 is coming from after the 131, can anyone explain this?
3
Answers
If you use
131 + "".split(",").map(Number)
you are adding"".split(",").map(Number)
to131
.You need to use
(131 + "").split(",").map(Number)
for your expected outcome.To understand it better, break down of what the script you provided does:
Removing
console.log
makes following:Evaluation happens firstly on
131
, then on"".split(',').map(Number)
, essentially making it equivalent to(131)
is just a number131
. Looking at"".split(',').map(Number)
, going from the leftmost:Will just return
['']
Will essentially be equivalent to
Since
Number('')
is0
, the result is[0]
. Coming back:Is just
1310
. There you go.The member accessor
.
has higher precedence than+
Thus in
131+"".split(',').map(Number)
the order of execution is (slightly abbreviated to focus on the important parts):"".split(',')
– split the empty string using a single comma. This results in[ "" ]
(see The confusion about the split() function of JavaScript with an empty string):[ "" ].map(Number)
– theNumber
function is applied to each member of the array. Since there the array after the split has a single empty string, it results in[ 0 ]
becauseNumber("")
is0
(see Number called using empty string, null, or undefined):131 + [ 0 ]
– adding a number and an array. This will first type coerce the array into a primitive then based on what kind of primitive it is (string or number) it will perform either numeric addition with131
or string concatenation (coercing the other operand to a string first). Arrays convert to a string primitive by joining all members together (see Why is [1,2] + [3,4] = "1,23,4" in JavaScript?). As the array only has a single member (a zero) the result is that single member as a string.Therefore the code concatenates 131 and 0 together.