Search code examples
javascriptprimitive-types

In JS, why am I able to use functions like toFixed() which resides in the prototype of the Number wrapper object on a primitive type?


In JavaScript, primitive types (number, string, etc.) are not objects. So, they don't have a [[prototype]] so can't use methods available in the [[prototype]] of some Objects.

Whereas Number, String are wrapper objects and can be used to create variables with the new keyword and we can use methods available in the prototype of the Number Object on those variables (created with the new keyword).

But in the given code, I created a primitive type variable and am able to use methods like toFixed() which resides in the Number Object.

This is confusing to me. Please elaborate on this.

let a = 6.678; //primitive type

a= a.toFixed(1); // toFixed() resides in prototype of Number Object

console.log(a); // 6.7

Solution

  • This has to do with something with a concept called "Autoboxing", Javascript sees that you're trying to access a property on the primitive type and hence for a very brief moment at runtime, it converts the primitive value to its corresponding Wrapper object and proceeds with the property call, it then converts the value back to primitive type in most of the cases.

    let a = 6.678; //primitive type
    
    a= a.toFixed(1); // JS converts a to "Number Object" and then the function is called
    
    console.log(a); // 6.7
    

    Here's a very good answer to it Does javascript autobox?