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():
const str = "hello";
console.log(str.toUpperCase()); // "HELLO"
How Does it Work?
Under the hood the following happens:
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:
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:
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
| Primitive | Object Wrapper |
|---|---|
string | String |
number | Number |
boolean | Boolean |
symbol | Symbol |
bigint | BigInt |
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.