Method of primitive

Method of primitive

Let’s start with a piece of code:

const name = "aniket";
name.toUpperCase(); // ANIKET

The name is a primitive but we are able to access a method on it as if it were some sort of object. But we know that primitive isn’t an object.
What is the story here?🧐

Primitive are simple values stored in memory, those are lightweight and extremely fast. Whereas an object is a collection of the key, value pairs, it is heavy but it allows to access some utility properties associated with the object that is very useful. The javascript people faced the dilemma where they wanted to put primitive for being lightweight and fast but also wanted to allow access useful methods on primitives.

The solution the came up with was:

As soon as the engine reaches line 2 it sees that you are trying to do property access on primitive, but as primitive itself doesn’t have methods on them. It momentarily wraps the primitive value into a corresponding type wrapper object that has these methods on them and that object exposes us the properties which we can use, as soon as the method is done executing it returns the result of the operation in a new memory space and deletes this wrapper object.

Constructors function

The constructor function String, Number, Boolean is for internal use only. Languages like Java allows us to explicitly creates a wrapper object that is also possible with JavaScript but those are not recommended and are for internal use only. A lot of things can go crazy if we use those.

// Insane Use 🙅‍♂️ Not recommended
const age = new Number(22);
typeof age; // "object" 😱
// Sane Use 😍
const age = Number("22");
// explicit type conversion

Recap with a question

Explain the console output in strict and non-strict mode?

const name = "Aniket";
name.last = "Jha";
console.log(name.last);

In strict mode on line 2, the engine sees that we are trying to create a property on internal momentarily created internal wrapper object so there occurs an error. For a non-strict mode the engine on line 2, allows you to create a property on momentarily created wrapper object but this object is thrown out of memory as soon as line 2 is done executing. On line 3 a new wrapper object is created momentarily but as this is different from previous it doesn't have thelastproperty and thus undefined is the output.

Conclusions

The primitive is indeed a simple value but the engine treats primitive especially if it sees there is property access on it by wrapping it in wrapper object and exposing us with useful methods and properties.

Did you find this article valuable?

Support Aniket Jha by becoming a sponsor. Any amount is appreciated!