Become a member
to unlock all features

Level Up!

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


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


    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.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    Instructor: 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.

    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.

    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.

    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.

    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.

    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.

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