Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Autoboxing Primitive Types in JavaScript

    Tyler ClarkTyler Clark
    javascriptJavaScript

    Primitive values by rule are not objects. However when we treat a primitive type like an object, such as getting the .length of a string, JavaScript will wrap that primitive type into an object. This new object is then linked to the corresponding built-in .prototype, so that we can utilize prototype methods on primitive types.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: If you're working in JavaScript, you're bound to hear someone tell you at one point in your career that everything in JavaScript is an object. However, there are primitive types that are used every day that are not objects. There is a reason though why this saying has come about and why it sticks around.

    Primitive types like our string here are not objects. They cannot be dotted into liken object. They don't have properties or methods on them. With this in mind, we should see some type of error when we get the length of a string, right?

    This is, again, because by rule, primitive values such as our string, number, Boolean, and etc., don't have properties on them, they don't have methods. However, as we see here, this is not the case. We get a returned value.

    What we can't see behind the scenes is JavaScript is doing something called autoboxing. Autoboxing happens automatically whenever we treat a primitive type like an object. In other words, whenever we try to .length on a string for example or toString a number, or get the value of a Boolean. Which means we are dotting into these primitives.

    JavaScript will wrap those primitives into an object. With this new object, it will connect it to the built-in object prototype that corresponds with that primitive type. Which thus, gives us access to the built-in dot prototype methods from the browser.

    Going back to my original statement of everything in JavaScript being an object, with primitive types, this is not true. But because of autoboxing where, when we treat primitive types like an object and JavaScript wrapping those primitives into objects, you can see why this misconception has started and is here today.