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' ?