Immutability Using Object Seal in Javascript

What if you want to allow changing props of an object, but do not want anyone to add new props? Well, that is what Object.seal is for.

Objects in Javascript cannot be made immutable by using a const keyword. const works on primitives. It can also make sure you don’t reassign value to an object.

const fruit = "apple";
fruit = "orange";
// TypeError: Assignment to constant variable.

const fruit = { name: "apple" };
fruit = { name: "orange" };
//TypeError: Assignment to constant variable.

But, const cannot prevent value in object from being changed.

const fruit = { name: "apple" };
fruit["color"] = "red";

console.log(fruit);
//{ name: 'apple', color: 'red' }

Previously you have seen how Object.freeze can be used to render an object completely immutable](/const-and-immutability-in-javascript/).

There are many real-world use cases where -

  1. You want program to continue changing values of existing props
  2. Prevent changing the attributes of the existing props
  3. Prevent further props from being added
  4. Prevent existing props from being deleted

This is where Object.seal helps..

const fruit = { name: "apple" };
Object.seal(fruit);

fruit["name"] = "orange";
console.log(fruit);
//{ name: 'orange' }

fruit["color"] = "orange";
console.log(fruit);
//{ name: 'orange' }
// no error in no-strict mode

You can also check whether an object is sealed at runtime using Object.isSealed(fruit).

comments powered by Disqus