Normally JavaScript numbers are primitive values created from literals:
var x = 123;
But numbers can also be defined as objects with the keyword new:
var y = new Number(123);
Example
var x = 123;
var y = new Number(123);
// typeof x returns number
// typeof y returns object
var y = new Number(123);
// typeof x returns number
// typeof y returns object
Do not create Number objects. It slows down execution speed.
The new keyword complicates the code. This can produce some unexpected results:
When using the == operator, equal numbers are equal:
Example
var x = 500;
var y = new Number(500);
// (x == y) is true because x and y have equal values
var y = new Number(500);
// (x == y) is true because x and y have equal values
When using the === operator, equal numbers are not equal, because the === operator expects equality in both type and value.
Example
var x = 500;
var y = new Number(500);
// (x === y) is false because x and y have different types
var y = new Number(500);
// (x === y) is false because x and y have different types
Or even worse. Objects cannot be compared:
Example
var x = new Number(500);
var y = new Number(500);
// (x == y) is false because objects cannot be compared
var y = new Number(500);
// (x == y) is false because objects cannot be compared
Note the difference between
(x==y) and (x===y).Comparing two JavaScript objects will always return
false. Practice Excercise Practice now