Reputation: 367
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
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