I am trying to understand the significance of the following code in javascript:
alert(+[]);
Displays 0
Is there any name for this? What concepts are involved?
I am trying to understand the significance of the following code in javascript:
alert(+[]);
Displays 0
Is there any name for this? What concepts are involved?
Share Improve this question asked Apr 12, 2014 at 19:39 asim-ishaqasim-ishaq 2,2306 gold badges33 silver badges58 bronze badges 1- possible duplicate of Why is ++[[]][+[]]+[+[]] = "10"? – GSerg Commented Apr 12, 2014 at 19:55
1 Answer
Reset to default 9The plus in prefix position can only act on numbers, so it 'coerces' its argument to a number. The empty array is not a number and can't be directly turned into one, so it is first coerced to the string representation of it (same as .toString()) which is "", and then "" is coerced to a number which is defined to be zero. You could also do the same thing with +""
or +[0]
or +[[[["0"]]]]
. It's not just a plus, you can get a numeric coercion in a number of situations (most arithmetic operators), which will all treat [] as if it is 0.
You can get some messed up coercions involving arrays, because when they are converted to strings they do not have the square brackets around them so an array nested inside another array has the same string representation and hence ends up as the same number.
My standard example that I enjoy giving in these situations is [["\t\n 987654321e-432"]]
. Yes, that will coerce to the number 0 if you stick it in an arithmetic expression (e.g. if ([["\t\n 987654321e-432"]] == 0) {alert('strange huh?')}
), despite not having a zero in it anywhere. That's because the string inside the doubly nested array coerces to a valid number too small to be represented in a javascript number, so it gets rounded to 0. The fact that the string to number coercion also ignores initial whitespace is also shown.