Skip to content Skip to sidebar Skip to footer

Why Using The Unary Operator + On An Array Gives Inconsistent Results In Javascript?

I was doing some testing converting values to integer in javascript and printing the output in the console when I came across with this strange behavior. console.log(+[]) ==> 0

Solution 1:

The Unary + operator internally uses the ToNumber abstract operation.

The ToNumber abstract operation, when applied to objects, calls the object's toString method (by way of the [[DefaultValue]] internal method) and then re-applies the ToNumber operation on the resulting string representation.

The interesting thing here is Array's toString method. Note that [false].toString() is quite different from [undefined].toString() or [null].toString(). When we inspect the specification for Array.prototype.toString, we see that internally it uses Array.prototype.join. Step 8 of the join algorithm says:

  1. If element0 is undefined or null, let R be the empty String; otherwise, Let R be ToString(element0).

Thus, any array containing a single null or undefined stringifies to the empty string (which ToNumber number-ifies to 0), while other values will stringify to some other string (which will then number-ify to NaN if the string is non-numeric).

+[undefined] is the same as +"", while +[false] is the same as +"false".


Post a Comment for "Why Using The Unary Operator + On An Array Gives Inconsistent Results In Javascript?"