Why does the new String * 1 return 0 in Javascript?

In JavaScript, why:

new String * 1 <- 0 

What exactly makes it return 0 , and why is the next value equal to NaN ?

 function Foo() { this.bar = 0; } new Foo * 5; <- NaN 
+6
source share
3 answers

If you use arithmetic operators like * , JavaScript will try to convert the type to a number. The empty string becomes 0 .

If you have, for example:

 new String("foo") * 1 

You will notice that it returns NaN because the conversion to number cannot be completed. What happens in your second situation.

+10
source

When you use arithmetic operators, operands are first converted to numbers.

In the first case, on the left side, you have an empty string. Empty lines will become 0 if they are converted to a number, in accordance with this in the specification.

StringNumericLiteral, empty or containing only a space, is converted to +0.

Since new String is just a string object with null characters, it is empty, and so your first expression evaluates to zero ( 0 * 1 ).


In the second case, new Foo returns an object that cannot be converted to a number. If the object cannot be converted to a number, NaN returned. Quoting the same section in the specification,

If the grammar cannot interpret the string as an extension of StringNumericLiteral, then the result of ToNumber is NaN.

That is why the result of NaN here ( NaN * 5 ).


You can check these things out yourself.

 console.log(+(new String())); // 0 console.log(+{}); // NaN 
+6
source

new String returns a String object that has a primitive value of ""

"" parsed as the number 0 .

So, when you do new String * 1 , it looks like 0 * 1 .

Your Foo object does not indicate any primitive value, so it cannot work for you, and you get NaN

If you write new String in your console, you should see a primitive value as a result

+1
source

All Articles