Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In Javascript, one of the reliable ways to convert a string to a number is the Number constructor:

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

Inspired by this question, I started wondering — what is the difference between the above and:

var x =new Number('09');

Number certainly looks better, but it seems like a slightly inappropriate use of a constructor. Are there any side effects or any difference to using it without the new? If there is no difference, why not, and what is the purpose of new?

like image 543
Nicole Avatar asked Mar 04 '10 17:03

Nicole


People also ask

What is new number in JavaScript?

Creates a new Number value. When Number is called as a constructor (with new ), it creates a Number object, which is not a primitive. For example, typeof new Number(42) === "object" , and new Number(42) !== 42 (although new Number(42) == 42 ).

What is number () in JavaScript?

Javascript Number() Function object: This parameter holds the objects that will be converted any type of javascript variable to number type. Return Values: Number() function returns the number format for any type of javascript variable. Example 2: Not a number is returned by the compiler.

What is the difference between ++ and += in JavaScript?

++ increases the integer by one and += increases the integer by the number of your choice.

Why is 0 not a number in JavaScript?

In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.


1 Answers

In the first case, you are using the Number Constructor Called as a Function, as described in the Specification, that will simply perform a type conversion, returning you a Number primitive.

In the second case, you are using the Number Constructor to make a 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 wrapper objects act on primitive values.

like image 75
Christian C. Salvadó Avatar answered Oct 09 '22 18:10

Christian C. Salvadó