This page looks best with JavaScript enabled

Immutability Using Object Seal in Javascript

 ·   ·  ☕ 2 min read

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.

1
2
3
4
5
6
7
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.

1
2
3
4
5
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..

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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).

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things