So, you want to protect an object that you created in JavaScript? With Object.seal() and Object.freeze(), you have two solid options that do slightly different things. While Object.seal() prevents new properties from being added to the object and marks all existing properties as non-configurable, it still lets you change the values of properties. Object.freeze() on the other hand prevents new properties from being added to the object, prevents existing properties from being removed, and prevents the values of existing properties from being changed.
Let’s take a look at two examples.
In the above example, we seal the object on line 14 and then test changing a property, adding a property, and deleting a property.
In the next example, we freeze the object on line 14 and then do the same thing to its properties.
You will notice that Object.isSealed() and Object.isFrozen() are also available for testing the objects.
Have a question, comment, concern, etc? Feel free to drop a comment, below.
The post Object.seal() vs Object.freeze() first appeared on Blog.jws.
Top comments (0)