I entered this statement in JSLint:
var number = new Number(3);
And received the following message:
Do not use Number as a constructor.
Why is that? The statement is creating a number object, not a primitive value, so I don't see why using new
is a problem.
EDIT: Thanks for all the responses. They've got me thinking further, so I posted a follow-up question here.
In addition to breaking === and typeof returning "object", using the Number constructor also changes the way the value is used in boolean contexts. Since "new Number(0)" is an object, not a literal value, it evaluates as "true" because it is not null. So for example:
var n1 = 0;
var n2 = new Number(0);
n1 == n2 // true
n1 === n2 // false
if (n1) {
// Doesn't execute
}
if (n2) {
// Does execute, because n2 is an object that is not null
}
Edit: Even worse than breaking === between number literals and Number objects, == doesn't even work between two Number objects (at least not in the intuitive way -- they test for identity, not equality).
var n1 = new Number(3);
var n2 = new Number(3);
alert(n1 == n2); // false
alert(n1 === n2); // false