What is the difference between "new number (...)" and "number (...)" in JavaScript?

In Javascript, one reliable way to convert a string to a number is with the Number constructor:

 var x = Number('09'); // 9, because it defaults to decimal 

Inspired by this question , I began to wonder β€” what is the difference between the above and:

 var x =new Number('09'); 

Number , of course, looks better, but it seems like a somewhat misuse of the constructor. Are there any side effects or any difference in using it without a new one ? If there is no difference, why not, and what is the purpose of the new ?

+7
javascript language-design language-features
source share
4 answers

In the first case, you use the Number Constructor, called as a function , as described in the Specification, which will simply perform the type conversion, returning you the Number primitive.

In the second case, you use the Number Constructor to create the Number object:

 var x = Number('09'); typeof x; // 'number' var x = new Number('09'); typeof x; // 'object' Number('1') === new Number('1'); // false 

The difference may be subtle, but I think it's important to notice how cover objects act on primitive values.

+10
source share

Number returns the value of a primitive number. Yes, it’s a little strange that you can also use a constructor function as a simple function, but that is how JavaScript is defined. Most built-in language types have strange and inconsistent additional features, such as, for example.

new Number creates an explicit Box object Number . Difference:

 typeof Number(1) // number typeof new Number(1) // object 

Unlike Java classes with primitive primitives, objects are not used at all in an explicit JavaScript Number expression.

I would not worry about using Number . If you want to be explicit, use parseFloat('09') ; if you want to be brief, use +'09' ; if you want to allow only integers, use parseInt('09', 10) .

+4
source share

SpiderMonkey-1.7.0:

 js> typeof new Number('09'); object js> typeof Number('09'); number 
0
source share

A number (without new ones) is not like the result in a primitive. The following example calls anyMethod () (if in the prototype Number).

 Number(3).anyMethod() 

While

 3.anyMethod() 

will not work.

0
source share

All Articles