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

Himansh
  • 879
  • 9
  • 15
  • 6
    Because when you do `.toString` it's not actually a primitive any more. If you're calling methods on a primitive, JS will wrap it into an object and then discard the object. It's sort of equivalent to doing `var temp = new Number(num); temp.toString()` – VLAZ Nov 05 '18 at 06:29
  • 1
    https://developer.mozilla.org/en-US/docs/Glossary/Primitive#Primitive_wrapper_objects_in_JavaScript – Danield Nov 05 '18 at 06:30

2 Answers2

11

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.

Derek Brown
  • 4,232
  • 4
  • 27
  • 44
  • 1
    so, what's the point of having primitives instead of just objects? given that all primitives (except of null, undefined... maybe?) will be coerced... – Thiago Dias Aug 19 '20 at 18:41
  • 3
    @ThiagoDias There is none, and it was considered a mistake in hindsight by the designers. It was done to make JavaScript more similar to Java, while the original goal was a language where everything is an object - and the "primitives" would just have been (immutable) objects. No wrapper types, no distinction between `String()` and `new String()`. – Bergi Feb 09 '22 at 19:57
1

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"
Deepak Uniyal
  • 323
  • 1
  • 4