How to Preserve Immutability of Objects in JavaScript ?
Last Updated :
26 Jul, 2023
Immutability is an issue when it comes to private or restricted objects. Sometimes we need to create new objects without making modifications or changes unintendedly to preserve the integrity of data. That’s why, we need to find a way to preserve the object states. In this article, we will understand the immutability of objects concept, along with understanding the different approaches to preserving the immutability of objects & correspondingly will know their basic implementation with the help of examples.
Immutability of Object
Immutability refers to ensuring the integrity of an object’s state. Immutable objects cannot be modified, add new, or delete existing properties. In this article, we will see how can we preserve the immutability of an object in JavaScript.
Different Techniques for preserving the immutability of objects
In JavaScript, we can preserve the immutability of objects using these methods:
JavaScript Object.freeze() method is used to freeze an object. Freezing an object does not allow new properties to be added to the object and prevents removing or altering the existing properties.
Syntax:
Object.freeze( obj );
Example: In this example, we will use Object.freeze() method to make the object immutable.
Javascript
const obj = { name: 'JavaScript' };
Object.freeze(obj);
obj.name = 'HTML'
console.log(obj.name);
|
The output clearly shows when the object is passed in the object.freeze() method it becomes immutable and can’t be modified.
The Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected.
Syntax:
let variablename1 = [ ...value ];
Example: In this example, we will create a new object using the spread operator preserving the state of the old object.
Javascript
const oldObject = { name: 'John' , age: 30 };
const newObject = { ...oldObject, age: 31 };
console.log(oldObject);
console.log(newObject);
|
Output
{ name: 'John', age: 30 }
{ name: 'John', age: 31 }
The Object.assign() method is used to copy the values and properties from one or more source objects to a target object.
Syntax:
Object.assign( target, ...sources );
Example: In this example, we will create a new object using object.assign() preserving the properties of existing objects.
Javascript
const obj1 = { name: 'JavaScript' };
const obj2 = Object.assign({},obj1)
obj2.name = 'HTML' ;
console.log(obj1.name)
console.log(obj2.name);
|
In Conclusion, the target is to preserve the immutability of objects which can be done either by freezing the object to make it immutable or by creating a new object with some modified properties. It can be achieved by using Inbuilt JavaScript methods like freeze(), Object.assign(), spread operator, etc.
Share your thoughts in the comments
Please Login to comment...