How does primitive types in Javascript have methods and Properties?

Viewed 1613
var num1 = new Number(5);
typeof(num1); //returns "object"
num1.toString(); //returns "5"

I understand that num1 being an object has a property .__proto__ via which it gets access to .toString() by going down the prototype (.__proto__) chain.

var num = 5;
typeof(num); //returns "number"
num.toString(); //returns "5"

In above case, num is a primitive type number. It means that it won't have any properties and methods. Then how's it able to get access to .toString() method?

2 Answers

It means that it won't have any properties and methods.

Javascript has a property called coercion when it comes to primitives; it silently converts the primitive to any object and then accesses the prototype method of the newly constructed number object.

Javascript coerces between primitives and objects. In this case number converts to object in order to access to string.

You can get the object using

//tweaking the to string
Number.prototype.toString = function() {
    return typeof this;
}
var num = 5;
typeof(num); 
num.toString(); //returns "object"
Related