Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 537
BitandDust Avatar asked Dec 25 '20 05:12

BitandDust


2 Answers

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?

like image 79
Sudhanshu Kumar Avatar answered Oct 26 '22 00:10

Sudhanshu Kumar


This is how the JavaScript engine works more or less. You're correct that the variable you've assigned to a is a primitive of Number type, but when you access a method on this primitive value, JS will create a special wrapper object (it will do this for each primitive type, i.e. strings) and gives it access to those methods.

The value will no longer be an object after you've accessed the method.

You can read more about it here: https://javascript.info/primitives-methods#a-primitive-as-an-object

@ashu's answer below includes the technical term which I wasn't actually aware of - so TIL! Apparently, this is called "Autoboxing"!

like image 24
Sherman Hui Avatar answered Oct 26 '22 02:10

Sherman Hui