WRAPPER OBJECTS: The most unknown thing for a Javascript developer

Luvdeep Katyal
3 min readApr 5, 2020

The concept of Wrapper Objects does exist in Java language, let us observe how it actually works in JavaScript. So let us begin with some primitives in JavaScript and the most common one is a String.

Let us just begin with a very common example that we all know since our childhood,

const name = “John Doe”;
and now we want to get the number of characters in the above string, we simply go for,

console.log(name.length);
and we get the length of the string as 8, alright that is no rocket science, we all do know that very well, but if i ask you that how does that work, if String is a primitive, how we are able to use a . (dot notation) ?

Now with the dot notation it does gives an idea that it is an Object, now obviously we performed Object.property, so is it really a primitive or an object.
A bit of confusing isn’t it ?

Alright, if you are too confused somewhere, you can also use the typeof keyword for a verification, but still i mean if you go for typeof name you are going to get it as a “string”.

I believe that lead to increasing your confusion level.

Alright so, let me reveal the “elephant in the room” here,
how it works is that JavaScript has equivalent objects for each of the primitive data types, like, String, Number, Boolean and Symbol.
So there is an equivalent object too, for a String primitive. Now actually when you try to access name.length this must actually fail, if name is a primitive, but when you access it’s length what JavaScript does is actually converts it into its equivalent Object and the length property becomes available to it and then it calls the length property of the Object String and that is how the length property works on a String primitive.

Now read carefully what happens when you do name.length the string is immediately wrapped up into a “wrapper object” and the length is accessed,
this is the concept of the Wrapper Object, and coming to the case whrer you try to get the typeof name it is still a “string”, this is due to the reason when the String primitive to an equivalent String Object is created it is not assigned to the name variable, it is just a temporary Object that is created, the length property is accessed from it and then the Object is actually discarded, like gone after just being created for a fraction of seconds to make the length property be accessed or just to make that operation work.

I hope now you have a clarity of what actually happens when we are using just a basic operation of String.length, this is how the Wrapper Objects come into the play.

So besides the String primitive there are equivalent Objects for the Number, Boolean and the es6 introduced Symbol primitive.

I hope you liked this unknown concept of Wrapper Objects In Javascript.

--

--