Skip to main content
Practice Problems

Boxing and unboxing in JavaScript

Boxing and Unboxing are processes of automatic conversion of primitive data types into object wrappers, and back. These processes occur implicitly in JavaScript when you work with methods and properties of primitives.


What is Boxing?

Boxing is wrapping a primitive in an object so you can use object methods and properties.

For example, string str = "hello" is a primitive. But you can still call method str.toUpperCase():

javascript
const str = "hello"; console.log(str.toUpperCase()); // "HELLO"

How Does it Work?

Under the hood the following happens:

javascript
const str = "hello"; const temp = new String(str); // Boxing: primitive → String object console.log(temp.toUpperCase()); // object method is called // temp is deleted, result is returned

Same works for Number, Boolean, Symbol and other primitives:

javascript
const num = 42; console.log(num.toFixed(2)); // "42.00" — primitive turns into Number object

What is Unboxing?

Unboxing is the reverse process: extracting primitive value from object wrapper.

Example:

javascript
const numObj = new Number(123); // object const primitive = numObj.valueOf(); // Unboxing console.log(typeof primitive); // "number"

Method valueOf() is used by JavaScript engine to get pure primitive value from wrapper object.

Types of Object Wrappers

PrimitiveObject Wrapper
stringString
numberNumber
booleanBoolean
symbolSymbol
bigintBigInt
Summary:

Boxing and Unboxing happen automatically in JavaScript. You don't need to manually convert primitives to objects — JavaScript does it for you when needed.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems