Autoboxing in Javascript.

OsamaAzhar
2 min readJul 1, 2023
Autoboxing in javascript

Let’s begin with a thought-provoking question:

How is it possible for a primitive data type in JavaScript to possess a property?

This phenomenon is achieved through the concept of autoboxing.

Autoboxing in JavaScript refers to the automatic process of wrapping a primitive value into an object using its corresponding wrapper class.

In JavaScript, autoboxing is a process performed internally when a property is accessed on a primitive value. This concept of autoboxing is not exclusive to JavaScript but is also implemented in other programming languages like C# and Java. With the exception of undefined and null, JavaScript provides wrapper classes (also known as wrapper types) for each primitive type, representing objects that correspond to those types.

So, for example, suppose that name is a variable holding a string “osama”. Accessing a property on name, like name.length would autobox name into a String object and then access the property on the object before deleting the object.

Consider this code:

var name = "Osama";
console.log(name.length);

When the expression name.length in line 2 is encountered, as stated before, autoboxing happens.

Behind the scenes, here’s what actually gets executed:

var name =”Osama”;
var nameBoxed = new String(name);
console.log(nameBoxed.length);
nameBoxed = undefined;

Firstly, the value of the variable ‘name’ is encapsulated within its corresponding wrapper type, String, and stored in a temporary variable named ‘nameBoxed’. This process is known as boxing.

Subsequently, the ‘length’ property is accessed on the ‘nameBoxed’ wrapper object, and the resulting value is then displayed in the console. As ‘nameBoxed’ is an object rather than a primitive, it is logical for it to have accessible properties.

Lastly, to illustrate the removal of the temporary variable from memory, javascript assigns ‘undefined’ to the temporary variable nameBoxed.

--

--

OsamaAzhar

Software Engineer | Javascript | Reactjs | HTML | CSS