Hello Everyone!
We all know that JavaScript objects are mutable by default. In this post, we'll look into few methods by which we can make objects immutable in JavaScript.
1) Object.preventExtensions
Object.preventExtensions() method prevents new properties from being added to an object.
In simple terms, New properties cannot be added to the object. But you can able to modify or delete the existing properties.
The example below will provide you more insights
2) Object.seal
Object.seal() method prevents new properties being added and existing properties being removed. seal() method will seal the object.
In simple terms, New properties cannot be added and existing properties cannot be removed. But modification to the existing properties are allowed.
3) Object.freeze
You probably might have heard about this before. Object.freeze() method freezes the entire object. This method makes the object unchangeable. New properties cannot be added. Existing properties cannot be deleted nor be updated.
Long story short
- Object.preventExtensions() - prevents addition of new properties
- Object.seal() - prevents addition of new properties and deletion of existing properties
- Object.freeze() - prevents addition of new properties. Deletion and modification of existing properties.
Thank you so much if you have read it so far. Please do share your thoughts on this.
If you liked reading this blog, please don't forget to like ❤️, comment 💬 and share 🤩 as your support means a lot to me.
Cheers! 🤙
Top comments (0)