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?
The Complete Full-Stack JavaScript Course! The plus(+) sign before the variables defines that the variable you are going to use is a number variable.
Unary plus (+) The unary plus operator ( + ) precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already.
The addition assignment operator ( += ) adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator.
JavaScript arrays are zero-indexed: the first element of an array is at index 0 , the second is at index 1 , and so on — and the last element is at the value of the array's length property minus 1 .
The 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With