๐Ÿš€ Transforming Mutable Objects to Immutable in JavaScript ๐Ÿš€

ยท

1 min read

Table of contents

No heading

No headings in the article.

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

No alt text provided for this image

โ„๏ธ 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:

No alt text provided for this image

๐Ÿ” Object.defineProperty ๐Ÿ” see code in attached image below
Another approach is to use Object.defineProperty to set specific properties as non-writable:

No alt text provided for this image

These techniques offer flexibility in controlling object mutability in JavaScript, allowing you to design more robust applications. # #JavaScript #ImmutableObjects

ย