Last time we talked about property descriptors and how we can use them to properly manipulate object properties to make them suit our needs as effectively as possible. In this post we are going to talk about some built in methods that can make our life with objects and their property descriptors much easier. Note that all the functions mentioned below operate on the object level. They apply to all properties and not just to one like property descriptors (link to article).
Let’s start with preventExtensions. This function will take your object and make its list of properties immutable. That means the function will disallow any further property additions to the object. If you try to add a property to that object afterwards the result will depend on the strictness of the code. In non-strict mode the property simply won’t be added, the program execution will continue as it otherwise normally do but the property won’t be added. So if you try to access it, you will get back the value ‘undefined’. In strict mode you get a TypeError. Check the following example that briefly demonstrates this useful functionality:
Note that preventExtensions does not protect the property’s against deletion. We successfully managed to delete the property ‘a’
The same example in strict mode:
If you try to execute this piece of code you will never get past line 13. The code will fail with this very descriptive error line: ‘Uncaught TypeError: Can’t add property d, object is not extensible’
preventExtensions is pretty useful when combined with strict mode because it gives you full control of your object’s lifetime. For example, say you have created a module that returns an object that for whatever reason you won’t to stay with its current properties. You can protect it with preventExtensions and any attempts to add unwanted properties will crash the script.
Next in line is seal. This function builds on top of preventExtensions to further protect your object’s properties. What seal does is it calls preventExtensions but also disables the configurability of every property. You can get the same result if you call preventExtension on your object and then modify the descriptor of every property and set configurable to false.
Check the following example, after the object is sealed we cannot add or remove any properties:
The last function for today is Object.freeze(). This function essentially calls Object.seal() on the object while also setting the writable status of every property to false. So that way you end up with a fully immutable object. See the example for more:
Of course if we try the same code in strict mode we will receive a TypeError when trying to add a new property.
That’s it for today. Three useful functions for full control of your objects. I hope you liked it and found it helpful. Check more JavaScript stuff here.