Nikita Shchypylov
Nikita Shchypylov

Reputation: 367

Is there a big difference between reference and primitive types of boolean, number etc.?

I rad, that we can create numbers as:

var num = 10;

and:

var num = new Number(10);

may i use only first variation of declaration?

Upvotes: 1

Views: 59

Answers (1)

Tarun Dugar
Tarun Dugar

Reputation: 8971

Yes, use the first one always, as it returns a primitive value.

The second method looks like it returns a primitive value but it doesn't. Infact, it returns an object with a boxed primitive value.

To explain this, lets declare two variables:

var a = 2;
var b = new Number(2);

The expression a == b will return true since JavaScript coerces b to a primitive value of 2. However, the expression a === b will return false as the types are different: a being a primitive and b being an object.

Upvotes: 4

Related Questions