DEV Community

Cover image for Do you know what πŸ“¦ Autoboxing in JS is?
Benjamin Mock
Benjamin Mock

Posted on β€’ Originally published at codesnacks.net

29 13

Do you know what πŸ“¦ Autoboxing in JS is?

Let's start with the question of "What are primitive types, and how are they defined?".

Primitive types don't have methods or properties on them.

Let's see some primitive types in JS. Let's try a number and a string.

const name = "Doggo"
const age = 7

console.log(typeof name) // string
console.log(typeof age) // number
Enter fullscreen mode Exit fullscreen mode

name has the primitive type string, age is a number. Both of these primitive types should not have any properties or methods on them. Let's check that:

console.log(name.length) // 5
console.log(age.toString()) // "7"
Enter fullscreen mode Exit fullscreen mode

Why does this work and not throw an error? It looks like both of the primitive types are actually objects! But they're not! They just behave like objects because of autoboxing. Whenever we try to access a method or property on a primitive, that primitive is wrapped into an object. That's called autoboxing. Autoboxing will connect the primitive to the related built-in prototype object. In our case that's String.prototype and Number.prototype. This gives us access to the prototype methods and properties.

This, for example, is the number prototype:

Number prototype


Want to get better at Web Development?
πŸš€πŸš€πŸš€subscribe to the Tutorial Tuesday βœ‰οΈnewsletter

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (3)

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt β€’

Why can't Java autoboxing just like JavaScript?

Collapse
 
kantakshay profile image
Akshay Kant β€’

Java is also using Autoboxing now a day's.

Collapse
 
kantakshay profile image
Akshay Kant β€’

.length is not a method, it's a property tho