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

    Prevent adding/deleting properties in a JavaScript object with Object.seal() method

    Tomasz ŁakomyTomasz Łakomy
    javascriptJavaScript

    Sometimes it's necessary to have a fixed set of properties on a JavaScript object, while also maintaining the option of changing those properties.

    In this lesson we are going to learn how to use Object.seal() method to prevent new properties from being added to it and marking all existing properties as non-configurable. Values of present properties can still be changed.

    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
    Transcript

    Transcript

    Instructor: 00:00 We have a simple JavaScript object which contains my name, my surname, my age, and country. We can see it in the console over here.

    00:07 We would like to ensure that this object can only have those four properties, while also being able to change them. In other words, what we'd like to do is, for instance, be able to increase the age of the user, but disallow adding a new property to the object. For instance, I would not be able to add a new city to this user object.

    00:28 In order to do that, we need to seal this object. Call Object.seal and pass this object as an argument. Now, I'm going to console.log this object after we change the age and after I try to set a new property, in this case, city.

    00:44 What we can see here is that I managed to increase my age -- I'm 29 now -- but even though I want to add a new property, this object has been sealed. Therefore, I'm not able to add something new.

    00:55 It's also not possible to delete a property from a sealed object. If I were to do delete userobject.name, then console.log it, what we're going to see as a result is that this object remains untouched.

    01:09 This behavior is a bit different under strict mode. If you were to enable strict mode by inaudible use strict, what we're going to see is that this attempt at adding a new property to this object is going to cause an error because you cannot add property to an object that is not extensible.

    01:27 That way, we can be extra sure that it is not possible to either add or delete a property from our sealed object.

    Discuss

    Discuss