Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does new String * 1 return 0 in Javascript?

Tags:

javascript

In JavaScript, why is:

new String * 1
<- 0

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

function Foo() { this.bar = 0; }
new Foo * 5;
<- NaN
like image 874
mariocatch Avatar asked May 25 '16 13:05

mariocatch


1 Answers

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

If you have, for example:

new String("foo") * 1

You will notice it returns NaN because the conversion to a number could not be completed. That's what happens in your second situation.

like image 180
Zomry Avatar answered Oct 12 '22 01:10

Zomry