Primitive as Objects

November 12, 2019

How does the following code work if primitives data types in javascript aren’t objects?

"Pawan Kumar".toUpperCase();

// "PAWAN KUMAR"

Are primitives also objects?

Let’s deep dive into the concept.

Conceptually, primitives don’t have methods.

What exactly happens behind the scene

That’s because when write something like

"Pawan Kumar".toUpperCase()

Javascript secrely creates an object wrapper and call the method for you:

(new String("Pawan Kumar")).toUpperCase()

and this object wrapper has all the methods of String Class. Once the operation is done, this object wrapper is collected by almighty garbage collection leaving the the primitive alone

Resouces

  1. do primitive strings have methods?
  2. The Secret Life of JavaScript Primitives
  3. Methods of primitives

Pawan Kumar

Written by Pawan Kumar who lives and works in New Delhi as a Full Stack developer.You should follow him on Twitter

Made with ❤️ in India.