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 Timescale

πŸš€ pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applicationsβ€”without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read 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

nextjs tutorial video

Youtube Tutorial Series πŸ“Ί

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series πŸ‘€

Watch the Youtube series