Prerequisites
To understand this article we need to know more about primitive data types in javascript.
There are seven data types in javascript:
- String
- Number
- Boolean
- Object
- Null
- undefined
- Symbol
Primitive data type means it is not an object and has no methods. All primitives are immutable (the value cant be altered). Let's see the following example:
we declared a primitive variable called result and a function that adds five to the result. The output is zero because addFive function creates a local copy of result and adds five to it and then the local copy variable is destroyed.
Keep in mind that there is a difference between altering the value and reassigning the value of a variable.
let number5 = 5;
number5 = 10; //(number5 variable is reassigned to a new value (10)
Now we are ready, let's back to our main topic.
Motivation
Have you ever wondered how this line of code even works?
You declared a primitive type (String) but still, you can use toUpperCase method, one of String object methods, how is that possible? another good question, if we can use String methods on str then we can treat it as an object and set properties on it like this one :
But it outputs undefined! sounds weird right?
Explanation
If you try to access properties or set a new property on a string primitive type, javascript will create a temporary object wrapper implicitly on it using String constructor function. See the following example:
As you can see, a temporary object wrapper was created when you tried to set the custom property to str, and the result is 1, after that the temporary object wrapper is removed and the custom property doesn’t exist anymore.
Except for null and undefined, all primitive values have object equivalents that wrap around the primitive values.
Keep in mind that javascript engine doesn’t keep this wrapper object around, as soon as the work of the method or other property is done, it is disposed of.
Thank you for your time, please Don’t hesitate to comment below if you have any questions.
Top comments (3)
That's a point !
Hi Abdel, nice content. However, seems like the first example and the underlying content doesn’t match. Apart from that i have one query, do these primitive wrapper objects are Mutable?
Hi Rohtash, sorry for the confusing, I updated the example. Regarding your question, Objects, in general, are mutable, so primitive wrapper objects are considered mutable as well, but even if you tried to modify it, it will be useless and you will not notice it because javascript performs these steps when primitive wrapper are created: