Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why a plus sign before array notation in javascript returns zero

Tags:

javascript

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?

like image 796
asim-ishaq Avatar asked Apr 12 '14 19:04

asim-ishaq


People also ask

What is plus sign in front of variable JavaScript?

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.

What does plus sign do in JavaScript?

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.

What does it mean to write two plus signs after a number type variable JavaScript?

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.

Does JavaScript array start at 0?

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 .


1 Answers

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.

like image 52
kybernetikos Avatar answered Sep 27 '22 20:09

kybernetikos