Let’s start with a piece of code:
const name = "aniket"; name.toUpperCase(); // ANIKET
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?🧐
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.
The constructor function
// 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);
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 the
lastproperty and thus
undefined is the output.
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!