⚠️ This lesson is retired and might contain outdated information.

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

Tomasz Łakomy
InstructorTomasz Łakomy
Share this video with your friends

Social Share Links

Send Tweet

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.

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.