Protect a JavaScript Object from Changes with Object.freeze()
In this lesson we'll learn how to prevent changes to an object in JavaScript using the built in Object.freeze() method. Once an object has been passed to Object.freeze(), no properties can be added, removed, or changed.
Duration
2 min
Access
Free
Transcript
Available
In this lesson we'll learn how to prevent changes to an object in JavaScript using the built in Object.freeze() method. Once an object has been passed to Object.freeze(), no properties can be added, removed, or changed.
This is helpful in a variety of situations, particularly with preventing inadvertent changes to an object's data throughout a codebase.
Video Transcript
Mark Foster: Let's pretend we've received a simple object of user permissions from our API. We know these values are not going to change in our application, and we want to protect them from any accidental changes. We want this object to be read-only.
Right now, this is a normal object, so we can make any changes that we would want. We could, for instance, change the isAdmin flag to true. We could set a newProperty to "Hello." We could even delete the allowUpdates property. If we save that, take a look at the results, everything we did took effect, as we would expect.
You notice we did use a const declaration up here, but as we can see, that did not protect our object from any of our operations. They all took effect. All that does is keep us from reassigning this PERMISSIONS variable to a new object or value. If we try to do something like this where we set PERMISSIONS to a new object, we're going to get a type error over here in the console.
Const does not protect our object from changes, but there is a built-in JavaScript method to not allow changes to an object, and that is Object.freeze().
If we take our PERMISSIONS object and pass it into Object.freeze(), save the file, and take a look at the output, we'll see here that we are getting the same object that we started with. All of our operations that happened after Object.freeze() did not take effect.
In fact, if we were to enable strict mode, we will get a type error if we try to make changes to an object that has been passed to Object.freeze(). Once an object has been frozen, there's no way to unfreeze it. It's a great way to take an object you want to protect and make sure that no changes can be made.