šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Working with read-only or immutable objects in Javascript

In Javascript, we can use the const keyword to define constants for primitive types.

const x = 10;
x = 20;
// Uncaught TypeError: Assignment to constant variable.

But if want to use it so that we create a "constant object" we will see that can we can still modify the values of that object.

const dog = {
    color: "brown", 
    name: "Spike"
}
dog.color = "red";

And even more, we can even add or remove the properties of the object:

dog.age = 5;
delete dog.name;
// the "const" object is now modified to 
// dog = {
//  color: "brown", 
//  age: 5
// }

So, is there is a way to create a read-only object in Javascript? Yes, there is. We can do it in various ways by using one of the below methods.

Object.preventExtensions() - prevent adding new properties to objects

Object.preventExtensions(dog);
dog.age= 5;
// can't add the new prop age

Keep in mind that you will still be able to remove the properties of the object. Also, note that Object.isExtensible() will test if we can add new props to an object.

Object.isExtensible(dog); 

Object.seal() - prevent adding and removing properties to objects

Object.seal(dog);
dog.age= 5;
// can't add the new age prop
delete dog.name;
// can't delete the name prop

Note that with the seal() you will still be able to change the values of the properties. The complementary Object.isSealed() will test if we can add or remove properties from an object.

Object.isSealed(dog); 

Object.freeze() - Prevent any change into an object.

Object.freeze(dog);
dog.age= 5;
// can't add the new age prop
delete dog.name;
// can't delete the name prop
dog.color = "red";
// can't change the color prop

As with the isExtensible() and isSealed() we have Object.isFrozen() that will tell us if we can add, remove or change any value in an object.

Object.isFrozen(dog); 

By default, the above methods will not throw any errors, but if you have strict mode enabled you will also get errors when trying to modify an immutable object.

Also of them are irreversible operations. So once you have selaled an object you can't un-seal it.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *