Limit Changes to a JavaScript object with Object.seal()

Mark Foster
InstructorMark Foster

Share this video with your friends

Send Tweet
Published a year ago
Updated 10 months ago

In this lesson we'll learn how to limit the types of changes that can be done to an object in JavaScript using the built in Object.seal() method. Once an object has been passed to Object.seal(), existing properties can be updated, but no new properties can be added and no properties can be deleted.

This is helpful in a variety of situations, particularly with preventing inadvertent changes to an object's structure throughout a codebase, while still allowing for updates.

Mark Foster: [0:00] Here we've got a simple JavaScript object. In our application we'll be using this to track the number of coins a user has. We'll need to allow updates to these properties as needed. For instance, we can increment pennies and we can set dimes to 7.

[0:15] In our application we only want to handle these four coin types. We want to make sure no new properties get added, and we want to make sure none of these get deleted.

[0:24] Currently, since this is just a normal JavaScript object, we can add a newCoin or delete quarters. If we save and take a look at the output, all that took effect.

[0:34] You might think this const declaration could help us here, but as we saw, const does not protect the contents of our object itself. All it does it keeps us from really assigning coins to an entirely new object or value. If we try to do something like this, we'll get a TypeError: Assignment to a constant variable.

[0:51] We want to allow changes to these properties, but we don't want to allow any new properties or deleting of properties. It turns out JavaScript has a built-in method to allow us to do just that, and that is Object.seal().

[1:04] If we pass our coins object into Object.seal, save and take a look at the output, we'll notice we have the original properties that we had when we started. These update operations took effect, but our newCoin and our deleting of quarters did not take effect.

[1:21] In fact, if we were to enable strict mode on this file, save and take a look, we get a TypeError if we try to do an invalid operation after the object has been sealed.

[1:34] Object.seal is a great way to take an object, still allow updates to its existing properties, but not to allow any new properties to be added, and not allow anything to be deleted.