Numbers Can be Objects

Normally JavaScript numbers are primitive values created from literals:
   define variable = 123;  <== typeof returns number

But numbers can also be defined as objects with the keyword new:
   define variable = new Number(123);  <== typeof returns object

Don't create Number objects. They slow down execution speed, and produce nasty side effects. Numbers and objects cannot be safely compared, because JavaScript objects cannot be compared, as demonstrated in the example below:

HTML file: Displayed by browser:
<body>
<p><strong style="color:#dc143c; font-size:18px;">#1:</strong> When using the == equality operator, equal numbers looks equal if they have equal values, even though one is a number and the other is an object. Numbers and objects cannot be safely compared:</p>
<p id="demo1"></p>
<hr />
<p><strong style="color:#dc143c; font-size:18px;">#2:</strong> When using the === equality operator, equal numbers are not equal, because the === operator expects equality in both type. The value here is false because x and y have different types :</p>
<p id="demo2"></p>
<hr />
<p><strong style="color:#dc143c; font-size:18px;">#3:</strong> Or even worse. JavaScript objects cannot be compared because even if they have the same defined values, their variable names do not match:</p>
<p id="demo3"></p>
<script>
    var x = 500;      // x is a number
    var y = new Number(500);    // y is an object
    var z = new Number(500);    // z is an object
    document.getElementById("demo1").innerHTML =    // THIS IS #1
    "If x = 500 and y = new Number(500), then (x==y) is " + (x==y);
    document.getElementById("demo2").innerHTML =    // THIS IS #2
    "If x = 500 and y = new Number(500), then (x===y) is " + (x===y);
    document.getElementById("demo3").innerHTML =    // THIS IS #3
    "If both y and z are defined = new Number(500), then (y==z) is " + (y==z);
</script>
</body>

#1: When using the == equality operator, equal numbers looks equal if they have equal values, even though one is a number and the other is an object. Numbers and objects cannot be safely compared:


#2: When using the === equality operator, equal numbers are not equal, because the === operator expects equality in both type. The value here is false because x and y have different types :


#3: Or even worse. JavaScript objects cannot be compared because even if they have the same defined values, their variable names do not match:


BackTable of ContentsNext