Deep dive into JavaScript Primitive Data-types and Auto-boxing — Nuts and Bolts series

laxmena
2 min readOct 18, 2023

--

Photo by Blake Connally on Unsplash

JavaScript primitive is a data-type which is not an object, and has no methods or properties. Primitives are the lowest level of JS implementation, and they cannot be boiled down further.

Primitive data types available in JavaScript:

  1. string
  2. number
  3. bigint (Added in ES11)
  4. boolean
  5. symbol (Added in ES6)
  6. undefined
  7. null

Note: These primitives are not to be confused with variables. Variables are containers that hold data, they are mutable. Whereas, primitives are immutable.

var fruit = "apple"

Here fruit is a variable, which points to the primitive string value — “apple”.

var fruit = "orange"

Variable fruit can be made to point to a different value like “orange” in this case, so they are mutable. But for primitives, the value cannot be modified.

“apple” remains the same, JavaScript doesn’t provide any tools to modify the value of the primitives.

Getting back to the other point that I mentioned previously: Primitives don’t have any methods.

Contradicting to my claim the following expressions seems to work amazingly well:

Case 1:

> "Hello world".substring(6)

Output: 'world'

Case 2:

> (1).toExponential()

Output: '1e+0'

When JavaScript primitives are not supposed to have any methods associated with them, how does substring() and toExponential() work?

How does it work?

It all has to do with what happens behind the scenes in JavaScript.

When JavaScript sees an expression with primitives, JavaScript does something called Auto-boxing. When it realizes that a method is being called on a primitive type, it tries to wrap this primitive object using inbuilt JavaScript classes to make JavaScript wrapper objects.

Primitives vs Wrapper objects examples:

Primitive type: string | JavaScript wrapper object: String
Primitive type: number | JavaScript wrapper object: Number

This wrapper object contains the definition of the methods that were invoked in the examples.

JS executes those methods and returns the results.

I felt this is a really interesting behavior of JavaScript.

Have you encountered this scenario before? Or do you have any experiences from your work along these lines, would love to hear them!

--

--