If we add a method to Number function (or Boolean or String) like this
Number.prototype.sayMyNumber = function(){
return "My number is " + this;
}
and then create a number object assign it to a variable
var num1 = new Number(34);
num1.sayMyNumber(); // it says "My number is 34"
This is fine and expected as we created 'Number' object.
Similarly, if I create a primitive variable
num2 = 34;
num2.sayMyNumber(); // it says "My number is 34"
Surprisingly, num2 also has a method sayMyNumber() even though we did not create a Number object explicitly.
Then I tried it like this,
34.sayMyNumber(); // error, this does not work
Why does num2 work?
Update
This is a follow up question that I asked in the comment section, I am putting it here for better visibility
Below answers mention that num2 is considered as a 'Number' object internally. This further confuses me.
typeof num1 === "number" // returns false
typeof num2 === "number" // returns true
typeof num1 === "object" // returns true
typeof num2 === "object" // returns false
Does this not mean that num2 is not an "object" ? If it is not an "object" then how can it be an instance of 'Number' ?
The primitive type Number has a corresponding object representation, which you can create with new Number
. This is an object and is therefore of a different data type than the primitive type Number.
If you call Number(34)
(without new
) an object isn't created, but the Number function performs a type conversion, to a primitive number value.
var num1 = new Number(34); // object
var num2 = 34; // primitive
When you call sayMyNumber()
on the primitive number num2
, JavaScript internally converts the primitive temporarily to its equivalent object version. And because you added sayMyNumber()
to Number.prototype
you have access to the function.
The reason 34.sayMyNumber()
doesn't work is because when JavaScript engine parses your source code, it has to interpret just what a dot means in a given context. In the case of 34.sayMyNumber()
the dot is potentially ambiguous. Does it mean the decimal separator? Or does it mean object member access? JavaScript opts to interpret all integers followed by a dot as representing part of a floating point number. But as there is no such number 34.sayMyNumber(), it raises a SyntaxError. Read more here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With