๐ Transforming Mutable Objects to Immutable in JavaScript ๐
Table of contents
In JavaScript, the ability to control the mutability of objects can be a game-changer. Let's explore three methods to make objects immutable, ensuring they remain unchangeable:
const person = { firstName: "atul", lastName: "bansal"};
๐ Object.seal ๐ see code in attached image below
Object.seal(person) allows you to lock an object down, preventing the addition or deletion of properties. However, you can still modify the property values. Take a look
โ๏ธ Object.freeze โ๏ธ see code in attached image below
Object.freeze(person) takes it a step further by making the object completely immutable. No additions, deletions, or modifications are allowed:
๐ Object.defineProperty ๐ see code in attached image below
Another approach is to use Object.defineProperty to set specific properties as non-writable:
These techniques offer flexibility in controlling object mutability in JavaScript, allowing you to design more robust applications. # #JavaScript #ImmutableObjects
Subscribe to my newsletter
Read articles from Atul Bansal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Atul Bansal
Atul Bansal
Full Stack web Developer with 4+ years of Experience