DEV Community

Cover image for Javascript Boxing and Unboxing
ikbal arslan
ikbal arslan

Posted on

Javascript Boxing and Unboxing

Boxing

Javascript primitive data types are not an object so it shouldn't have methods and properties right?

Did you know that number and string primitive values can act like reference types so we can use methods and properties with them?

By default when we run the javascript objects inside of the __proto__ and we can use them in our code.
some of the objects inside are String and Number

Whenever we want to use methods or properties on primitive types:

  • if the type is a string it will wrap it with the String object from proto
  • if the type is a number it will wrap it with the Number object from the proto

This is called auto-boxing, think of the objects as a big box and we put primitive types as small boxes inside of the objects so we can use all the methods and properties.

For some reason, we can use methods and properties with primitive types. The reason is called boxing and it is automatically applied to primitive types.

var car = "ford";

console.log(car);
car.length // 4
Enter fullscreen mode Exit fullscreen mode

Image description

In this case, the type of the car is a string which is a primitive type
in the console.log(car) everything will be normal.
but in the next line we are using a method that only reference types have so behind the scenes javascript will put this variable inside of the String object from proto so we can access to the methods.


UnBoxing

{a : 4} > {a : 5}
Enter fullscreen mode Exit fullscreen mode

In this case, when we want to compare two objects we can't do that. we can only compare primitive types.

To do this calculation we need to convert them to the primitive types. for this, we have a method which is ToPrimitive(). it will call this method default to convert them to primitive types.

So behind the scenes, the calculation will be like this

ToPrimitive({a:4}) > ToPrimitive({a:5})  //false
Enter fullscreen mode Exit fullscreen mode

Since we are converting reference types to primitive types that called un-boxing.

Top comments (1)

Collapse
 
mitchiemt11 profile image
Mitchell Mutandah

Nice read!