Hey folks 👋!
I am currently learning javascript. I came across something that I never heard before. I learned about autoboxing and wrapper. I knew wrappers are used in java but had no clue they exist in javascript.
Look at the code given below -
Strange isn't it? We declared name
and age
variables. We didn't declare objects. So where are these methods and attributes coming from?
So whenever we try to access functions from the prototype of primitives, under the hood, javascript wraps these variables to its wrapper types.
See above, this is how they are initialized as temporary wrapper objects by the javascript engine.
What are wrapper objects?
Wrapper objects convert primitive data types to object type. This is the same case in java where primitives are converted to objects by wrappers classes because collection framework doesn't store primitives. The primitives in javascript are number
, string
, boolean
, undefined
, null
and symbol
. Their wrapper objects are Number
, String
, Boolean
as follows.
How are they temporary?
Whenever this conversion from primitive to object happens, the objects are dumped after a single-use.
We are overriding toUpperCase()
and returning "toUppercase", still toUpperCase()
was not overridden. Do you know why? Yes because they are temporary. They are invoked when we are accessing functions in the prototype and dumped immediately.
I'd be coming with a follow-up article where we'd discuss what's need for autoboxing.
Thank You for reading!
Top comments (0)