Ian Hazzard
Ian Hazzard

Reputation: 7771

What is the difference between var num=30 and var num=new Number(30) in JavaScript?

It seems like there are so many different ways to do the same things in JavaScript. Is there any difference in using the "new" keyword in JavaScript for numbers and just entering a number? I see no difference between:

var num = 30;

var num = new Number(30);

It's the same with strings (and arrays):

var str = "hello";

var str = new String("hello");

Why would someone use one method over the other? They seem the same to me, and it's just more typing anyway.

Upvotes: 0

Views: 319

Answers (1)

anddoutoi
anddoutoi

Reputation: 10111

The first creates a primitive. The other an object.

In theory there is a difference but in practice none. The JavaScript engine automagicly boxes a primitive to an object when it needs to be an object.

var myPrimitiveNumber = 42;
// calling .toFixed will 'box' the primitive into a number object,
// run the method and then 'unbox' it back to a primitive
console.log( myPrimitiveNumber.toFixed(2) );

The only usage I've found is if you want to return a primitive from a constructor function.

function Foo() {
    return 42;
}

var foo = new Foo();
console.log(foo); // foo is instance of Foo

function Bar() {
    return new Number(42);
}

var bar = new Bar();
console.log(bar); // bar is instance of Number

Upvotes: 5

Related Questions