Table of contents
1.
Introduction
2.
AutoBoxing
3.
Manual Boxing 
4.
Unboxing
5.
Frequently Asked Questions
5.1.
How can we access an object's inbuilt methods?
5.2.
What is JavaScript coercion?
5.3.
What is the difference between Boxing and Unboxing?
5.4.
What is == and === in JavaScript?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

JavaScript Boxing and Unboxing

Author Amit Singh
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

This article will help you understand the conversion of primitive data types to object data types, i.e., boxing and it's vice-versa, known as unboxing.

In Javascript and other languages which are based on object-oriented programming, primitive values don't have any properties or methods. If you want to use them, you need to use a wrapper to convert them into object data types.

Primitive data types are the simplest elements of a programming language. JavaScript has six primitive types: string, Number, boolean, null, undefined, and symbol, and everything else is an object.

In this article, we are going to take a deep dive into the Javascript Boxing and Unboxing with examples:

AutoBoxing

Boxing is the process in which a primitive value is wrapped in an Object. When a primitive type is treated as an object, e.g., calling the toUpperCase() function, JavaScript would automatically wrap the primitive type into the corresponding object type. This new object type is then linked to the related built-in <.prototype>, so you can use prototype methods on primitive types.

Let's see an example:

//String primitive name
const name = "CODINGNINJA";
console.log(name.toLowerCase());
console.log(name.substring(1));
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

codingninja

ODINGNINJA

 

From the above example, we can see that when we try to use a method on a primitive type, JavaScript automatically does the boxing, i.e., wrapping that primitive type into an object type. This autoboxing allows us to use the different methods of the String object.

Next, we’ll learn about the Manual Testing: 

Manual Boxing 

As we can see, AutoBoxing is quite easy to implement, but it has some issues too. It's not usually a good idea to directly use a boxed object wrapper because sometimes that generates results that are not expected at all.

Let’s try to understand this with an example: 

// 3 flags but all are "true". Even though we have given "false"
let flag1 = new Boolean(true)
if(flag1) { 
    console.log("inside flag1")
}
let flag2 = new Boolean(false)
if(!flag2) {
    console.log("inside flag2");
}
let flag3 = Object(false)
if(!flag3) {
    console.log("inside flag3");
}
You can also try this code with Online Javascript Compiler
Run Code

 

Output

Inside flag1

 

So, the issue with this program is that we are trying to create an object wrapper around a false value, but there is a catch: objects have a true value. So, we will have to use valueOf() to box the primitive data type in this case. 

Let's see how:

const b = Boolean(false)
if(!b.valueOf()) {
   console.log("its false");
}
You can also try this code with Online Javascript Compiler
Run Code

 

Output

it's false

 

As we can see, this approach is quite beneficial in the above case. But it is better to box implicitly as the browsers are optimized that way. Also, in a manual approach, the code becomes slower.

So, it is generally preferred to use an object data type instead of a primitive one.

Unboxing

Unboxing is converting the reference or object types to basic or primitive data types. It is the opposite of boxing or packing. 

One of the easiest ways to convert the object wrapper to the respective primitive data type is to use the valueOf() method.

Let us see an example:

let flag1 = Object(false);
console.log(flag1 == false)
console.log(flag1 === false)
console.log(flag1.valueOf() == false)
console.log(flag1.valueOf() === false)
You can also try this code with Online Javascript Compiler
Run Code

 

Output

true

false

true

true

 

The process of unboxing can be achieved implicitly (coercion).

Let us look at an example:

flag1 == false; // result is true
You can also try this code with Online Javascript Compiler
Run Code


You can practice by yourself with the help of Online Javascript Compiler for better understanding.

Must Read Fibonacci Series in JavaScript  jquery ajax

Frequently Asked Questions

How can we access an object's inbuilt methods?


You can utilize (.), i.e., dot operator, to call upon the methods embedded within a particular object in JavaScript. For instance - 
let human { … }
> human.functionName(args);

What is JavaScript coercion?


Type coercion is just like type conversion, but the only difference is that the coercion is performed implicitly or automatically by the JavaScript engine.

What is the difference between Boxing and Unboxing?


Boxing converts a value or primitive type to the type object. When the common language runtime or CLR boxes a value or primitive type, it creates a wrapper to wrap the value inside a System. Boxing is implicit; unboxing is explicit.

What is == and === in JavaScript?


= is used to assign values to a variable in JavaScript. == is used to compare two variables irrespective of the variable's data type. === is used to compare two variables, but this will check strict type, which means it will check datatype and compare two values.

Conclusion

Boxing and unboxing are important and regularly used practices. But in different languages or different implementations, the wrapper can consume more memory and take more time to run the code than primitive types. But, if we talk about higher-level data structures, the wrappers are very useful. That also increases flexibility in your code.

We have learned about boxing as well as unboxing. In boxing, we have seen how to achieve AutoBoxing and Manual Boxing. The pros and cons of both types of boxing. 

It is preferred to use boxing implicitly because browser engines are optimized. 

We hope that this article has provided you with the help to enhance your knowledge regarding boxing and unboxing in javascript and if you would like to learn more, check out our articles on JavaScript BOMType Conversion in JavaScript and Objects in JavaScript

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available, Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Merry Learning!

Live masterclass