First off, alert does always return undefined
. But it prints stuff on screen. console.log
gives you more detailed and colorful info though.
This problem has two parts. First one is that numbers are normally not Number
instance. The second is that two objects (two instances) of any kind are never exactly equal:
{}=={} // false
Not Number
problem
Now to the Number
issue. Although all numbers in JavaScript are technically a Number
, javascript does not treat them like that and they are not number instance. This is something I don't like very much, but it's what it is. If you create number by instance, it behaves as non-object value:
5 instanceof Number //false
typeof 5 // "number"
Creating number with Number
constructor creates an object, that acts as a Number
:
new Number(5) instanceof Number //true
typeof new Number(5) // "object"
It should be noted that this object is actually not very special. You can make your own number class:
function MyNumber(val) {
this.number = 1*val||0;
}
MyNumber.prototype.valueOf = function() {
return this.number;
}
This will work just as Number
object does. Of course, just as Number
object, this is lost when you do a math operation:
typeof (MyNumber(6)+MyNumber(4)) // "number"
Two object instances are never exactly equal
This is actually useful feature. But it betrays you here:
new Number(5)===new Number(5) //false
Number
instance will never be exactly equal to anything but itself.