Preventing Addition of New Properties to a Javascript Object with Object.seal()

javascript
Published on December 12, 2019

Use-Cases of this tutorial

  • Know how to "seal" an object so that new properties cannot be added.
  • Know about the Object.seal() method.
  • Know whether a given object is sealed or not.
  • Know how to catch the error if attempt is made to add a new property to sealed object.

The Object.seal() method seals an object. After an object gets sealed, no new properties can be added to it.

The Object.seal() method prevents addition of new properties to a Javascript object. However values of existing properties can be changed if required.

Object.seal() is meant for cases where several developers are working on a single Javascript application, and data needs to be passed around. This can be used by a developer to "seal" his data before passing it to the other developer. This prevents the data from being polluted by other developers.

var test = {
    a: 34,
    b: 67
};

// new property is added
test.c = 45;

// object is now sealed
Object.seal(test);

// addition of new properties cannot be done now
test.d = 57;

// existing properties can still be changed
test.b = 88;

// Object {a: 34, b: 88, c: 45}
console.log(test);

Checking whether a Given Object is Sealed or Not

The Object.isSealed() method can check whether a given object is sealed or not. If sealed, it returns a true, and false otherwise.

var test = {
    a: 34,
    b: 67
};

// false
console.log(Object.isSealed(test));

// object is now sealed
Object.seal(test);

// true
console.log(Object.isSealed(test));

Catching Error if Attempt is Made to Add New Property to a Sealed Object

If new properties are added to a sealed object, they will fail silently.

However in strict mode, if new properties are added, they will throw a TypeError Exception. This can be caught within a try .. catch block.

"use strict";

var test = {
    a: 34,
    b: 67
};

Object.seal(test);

// exception will be thrown in strict mode
try {
    test.c = 50;   
}
catch(error) {
    // can't define property "c": Object is not extensible
    console.log(error.message);
}
In this Tutorial