JavaScript Object Immutability

JavaScript Object.freeze() vs Object.seal()

Object immutability is an important concept in any programming language. It restricts object modifications and prevents unwanted changes.

In this article, I will discuss how we can implement object immutability in JavaScript using freeze() and seal() methods.

Need of Object Immutability in JavaScript

Before discussing freeze() and seal() methods, let’s discuss object immutability in JavaScript a bit more.

When creating an object in JavaScript and assigning it to a variable, it does not hold the object’s value. Instead, the variable has only a reference to the object we create.

For example, if we create an object called draftArticle and assigned it to another variable called publishedArticle, we will be copying the reference of draftArticle, not the values. So, if we make a change to the publishedArticle, it will also modify draftArticle values.

var draftArticle = { 
name: “Object Immutability”,
author: “Chameera Dulanga”,
publication: “Bits and Pieces”,
status: “In review”
};
var publishedArticle = draftArticle;
publishedArticle.name = “JavaScript Object Immutability”;
console.log(draftArticle);

Likewise, there can be accidental modifications for objects in your application and cause unexpected bugs. That’s where the need for object immutability comes in, and let’s see how we can use freeze() and seal() methods to address this challenge.

Object.freeze()

As the name implies, freeze() is used to freeze objects. So, if you want an object to be protected from changes, you can pass it to the freeze() method as follows. And it will return an immutable version of that object.

var draftArticle = { 
name: “Object Immutability”,
author: “Chameera Dulanga”,
publication: “Bits and Pieces”,
status: “In review”
};
var publishedArticle = Object.freeze(draftArticle);

Using isFrozen() method is the only way to verify that an object is made immutable using Object.freeze().

You can confirm that both publishedArticle and draftArticle are identical by using the strict equality operator. But, you won’t be able to make any changes to any of them

For example, let’s try updating and deleting existing property from both publishedArticle and draftArticle .

// Updating
draftArticle.name = "JavaScript Object Immutability";
publishedArticle.name = "JavaScript Object Immutability";
// Deletingdelete draftArticle.publication;
delete publishedArticle.publication;
console.log(draftArticle);
console.log(publishedArticle);

As you can see, none of the objects has been updated since they were frozen. If you try the above code in a strict environment, you will get errors when adding, updating, or deleting properties.

However, Object.freeze() method does not affect the nested objects.

So, if you freeze an object with a nested object, the properties of that nested object will not be immutable. For example, let’s create an immutable object named article and include a nested object called writer.

var article = { 
topic: “Object Immutability”,
publication: “Bits and Pieces”,
status: “In review”,
writer: {
'name': "Chameera Dulanga",
'number of articles': 100
}
};
var newArticle = Object.freeze(article);

Now, if you try to modify the above object, you won’t be able to make changes to the topic, publication or status. But, you can modify the name and number of articles within the writer object since freezing does not effects the nested objects.

article.topic = “JavaScript Object Immutability”;
article.writer.name = “K G C Dulanga”;
console.log(article);

If you need to freeze the nested objects and make them immutable, you need to follow a recursion approach to freeze level by level.

Note: Object.freeze() method can also be used to make arrays immutable.

Object.seal()

Object.seal() is another approach to make objects immutable. But, it is a bit different from freeze().

Object.seal() only protects the objects against adding and removing properties. It allows updating existing properties.

For example, let’s create a new object and perform add, edit, and delete operations.

var article = { 
name: “Object Immutability”,
author: “Chameera Dulanga”,
publication: “Bits and Pieces”,
status: “In review”
};
// Sealing the object
Object.seal(article);
// Adding new property
article["status"] = “In review”;
// Deleting
delete article["publication"];
// Updating
article.name = "JavaScript Object Immutability";

As you can see, adding and deleting properties into the objects has failed. But, the name attribute is successfully updated.

You can use isSealed() method to confirm the sealed status of an object.

In addition to that, Object.seal() also has shallow sealing behavior similar to Object.freeze() . Which means you need to you a recursive strategy to seal nested objects.

I think now you understand how we can make JavaScript objects immutable and the differences between freeze() and seal(). However, some of you might think that we can use const keyword to achieve the same result.

But, it is not the same. Let’s see why that is.

Const Keyword Does Not Make Objects Immutable

When we create an object using const keyword, it only prevents us from reassigning a value. But, we can update, add and delete properties of the created objec

const article = { 
name: “Object Immutability”,
author: “Chameera Dulanga”,
publication: “Bits and Pieces”
};
article.name = “JavaScript Object Immutability”;
delete article.publication;
article[“status”] = “In review”;

As you can see in the above example, I have added a new property, updated an existing one, and deleted one without issues.

So, the const keyword only provides assignment immutability. It does not provide value immutability.

Conclusion

In this article, I discussed 2 methods we can use to make JavaScript immutable.

In a nutshell, Object.seal() methods prevent updates, deletes, and adding new properties to an object and Object.seal() only prevents adding and deleting properties.

In addition to these 2 methods, we can use Object.preventExtensions() method to only prevent adding new properties to an object.

The following graph will give you a better understanding of the capabilities of these 3 methods.

There are no hard and fast rules to make objects immutable. But, using them can save you a whole lot of time from debugging for unexpected bugs.

Thank you for Reading !!!

Build with independent components, for speed and scale

Instead of building monolithic apps, build independent components first and compose them into features and applications. It makes development faster and helps teams build more consistent and scalable applications.

OSS Tools like Bit offer a great developer experience for building independent components and composing applications. Many teams start by building their Design Systems or Micro Frontends, through independent components.
Give it a try →

An independently source-controlled and shared “card” component. On the right => its dependency graph, auto-generated by Bit.

Learn More


JavaScript Object Immutability was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Chameera Dulanga

JavaScript Object.freeze() vs Object.seal()

Object immutability is an important concept in any programming language. It restricts object modifications and prevents unwanted changes.

In this article, I will discuss how we can implement object immutability in JavaScript using freeze() and seal() methods.

Need of Object Immutability in JavaScript

Before discussing freeze() and seal() methods, let’s discuss object immutability in JavaScript a bit more.

When creating an object in JavaScript and assigning it to a variable, it does not hold the object’s value. Instead, the variable has only a reference to the object we create.

For example, if we create an object called draftArticle and assigned it to another variable called publishedArticle, we will be copying the reference of draftArticle, not the values. So, if we make a change to the publishedArticle, it will also modify draftArticle values.

var draftArticle = { 
name: “Object Immutability”,
author: “Chameera Dulanga”,
publication: “Bits and Pieces”,
status: “In review”
};
var publishedArticle = draftArticle;
publishedArticle.name = “JavaScript Object Immutability”;
console.log(draftArticle);

Likewise, there can be accidental modifications for objects in your application and cause unexpected bugs. That’s where the need for object immutability comes in, and let’s see how we can use freeze() and seal() methods to address this challenge.

Object.freeze()

As the name implies, freeze() is used to freeze objects. So, if you want an object to be protected from changes, you can pass it to the freeze() method as follows. And it will return an immutable version of that object.

var draftArticle = { 
name: “Object Immutability”,
author: “Chameera Dulanga”,
publication: “Bits and Pieces”,
status: “In review”
};
var publishedArticle = Object.freeze(draftArticle);
Using isFrozen() method is the only way to verify that an object is made immutable using Object.freeze().

You can confirm that both publishedArticle and draftArticle are identical by using the strict equality operator. But, you won’t be able to make any changes to any of them

For example, let’s try updating and deleting existing property from both publishedArticle and draftArticle .

// Updating
draftArticle.name = "JavaScript Object Immutability";
publishedArticle.name = "JavaScript Object Immutability";
// Deletingdelete draftArticle.publication;
delete publishedArticle.publication;
console.log(draftArticle);
console.log(publishedArticle);

As you can see, none of the objects has been updated since they were frozen. If you try the above code in a strict environment, you will get errors when adding, updating, or deleting properties.

However, Object.freeze() method does not affect the nested objects.

So, if you freeze an object with a nested object, the properties of that nested object will not be immutable. For example, let’s create an immutable object named article and include a nested object called writer.

var article = { 
topic: “Object Immutability”,
publication: “Bits and Pieces”,
status: “In review”,
writer: {
'name': "Chameera Dulanga",
'number of articles': 100
}
};
var newArticle = Object.freeze(article);

Now, if you try to modify the above object, you won't be able to make changes to the topic, publication or status. But, you can modify the name and number of articles within the writer object since freezing does not effects the nested objects.

article.topic = “JavaScript Object Immutability”;
article.writer.name = “K G C Dulanga”;
console.log(article);
If you need to freeze the nested objects and make them immutable, you need to follow a recursion approach to freeze level by level.
Note: Object.freeze() method can also be used to make arrays immutable.

Object.seal()

Object.seal() is another approach to make objects immutable. But, it is a bit different from freeze().

Object.seal() only protects the objects against adding and removing properties. It allows updating existing properties.

For example, let’s create a new object and perform add, edit, and delete operations.

var article = { 
name: “Object Immutability”,
author: “Chameera Dulanga”,
publication: “Bits and Pieces”,
status: “In review”
};
// Sealing the object
Object.seal(article);
// Adding new property
article["status"] = “In review”;
// Deleting
delete article["publication"];
// Updating
article.name = "JavaScript Object Immutability";

As you can see, adding and deleting properties into the objects has failed. But, the name attribute is successfully updated.

You can use isSealed() method to confirm the sealed status of an object.

In addition to that, Object.seal() also has shallow sealing behavior similar to Object.freeze() . Which means you need to you a recursive strategy to seal nested objects.

I think now you understand how we can make JavaScript objects immutable and the differences between freeze() and seal(). However, some of you might think that we can use const keyword to achieve the same result.

But, it is not the same. Let’s see why that is.

Const Keyword Does Not Make Objects Immutable

When we create an object using const keyword, it only prevents us from reassigning a value. But, we can update, add and delete properties of the created objec

const article = { 
name: “Object Immutability”,
author: “Chameera Dulanga”,
publication: “Bits and Pieces”
};
article.name = “JavaScript Object Immutability”;
delete article.publication;
article[“status”] = “In review”;

As you can see in the above example, I have added a new property, updated an existing one, and deleted one without issues.

So, the const keyword only provides assignment immutability. It does not provide value immutability.

Conclusion

In this article, I discussed 2 methods we can use to make JavaScript immutable.

In a nutshell, Object.seal() methods prevent updates, deletes, and adding new properties to an object and Object.seal() only prevents adding and deleting properties.

In addition to these 2 methods, we can use Object.preventExtensions() method to only prevent adding new properties to an object.

The following graph will give you a better understanding of the capabilities of these 3 methods.

There are no hard and fast rules to make objects immutable. But, using them can save you a whole lot of time from debugging for unexpected bugs.

Thank you for Reading !!!

Build with independent components, for speed and scale

Instead of building monolithic apps, build independent components first and compose them into features and applications. It makes development faster and helps teams build more consistent and scalable applications.

OSS Tools like Bit offer a great developer experience for building independent components and composing applications. Many teams start by building their Design Systems or Micro Frontends, through independent components.
Give it a try →

An independently source-controlled and shared “card” component. On the right => its dependency graph, auto-generated by Bit.

Learn More


JavaScript Object Immutability was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Chameera Dulanga


Print Share Comment Cite Upload Translate Updates
APA

Chameera Dulanga | Sciencx (2021-10-07T17:50:25+00:00) JavaScript Object Immutability. Retrieved from https://www.scien.cx/2021/10/07/javascript-object-immutability/

MLA
" » JavaScript Object Immutability." Chameera Dulanga | Sciencx - Thursday October 7, 2021, https://www.scien.cx/2021/10/07/javascript-object-immutability/
HARVARD
Chameera Dulanga | Sciencx Thursday October 7, 2021 » JavaScript Object Immutability., viewed ,<https://www.scien.cx/2021/10/07/javascript-object-immutability/>
VANCOUVER
Chameera Dulanga | Sciencx - » JavaScript Object Immutability. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/10/07/javascript-object-immutability/
CHICAGO
" » JavaScript Object Immutability." Chameera Dulanga | Sciencx - Accessed . https://www.scien.cx/2021/10/07/javascript-object-immutability/
IEEE
" » JavaScript Object Immutability." Chameera Dulanga | Sciencx [Online]. Available: https://www.scien.cx/2021/10/07/javascript-object-immutability/. [Accessed: ]
rf:citation
» JavaScript Object Immutability | Chameera Dulanga | Sciencx | https://www.scien.cx/2021/10/07/javascript-object-immutability/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.