JavaScript Object.seal()

The Object.seal() method seals the given object. This prevents new properties from being added to the object and marks all the existing properties as non-configurable.

Example

const obj = {
  name: 'John',
  age: 30
};

// seal the obj object Object.seal(obj);
// throws an error in strict mode // silently fails in non-strict mode obj.address = "New York"; console.log(obj.address); // Output: undefined

seal() Syntax

The syntax of the seal() method is:

Object.seal(obj)

The seal() method, being a static method, is called using the Object class name.


seal() Parameters

The seal() method takes in:

  • obj - the object that is to be sealed.

seal() Return Value

The seal() method returns the object being sealed i.e. obj.


Example 1: JavaScript Object.seal()

let obj = {
  foo: "bar",
  func: function () {},
};

// before sealing, properties can be
// added, modified, or removed
obj.foo = "JavaScript";
obj.value = 5;
delete obj.func;

console.log(obj);

// Output: { foo: 'JavaScript', value: 5 } 

// seal the object let o = Object.seal(obj);
// can still change property values // as it is writable by default obj.foo = "bar1"; console.log(obj); // Output: { foo: 'bar1', value: 5 } // no other change happens, fails silently obj.foo1 = "bar"; delete obj.foo; console.log(obj); // Output: { foo: 'bar1', value: 5 }

From the example above, it is clear that we can add, modify, or remove properties from the obj object before it is sealed.

After sealing obj with the seal() method, we

  • can modify existing writable properties like foo and value,
  • cannot add new properties to obj (attempt fails silently in non-strict mode)

Example 2: Redefine Property After seal()

const obj = {
    foo : "bar",
}

// seal the object
Object.seal(obj);

// redefine "foo" using defineProperty()
Object.defineProperty(obj, "foo", {
  get: function () {
    return "g";
  },
});

// Output: TypeError: Cannot redefine property: foo

In the above example, the foo property cannot be redefined as the object is already sealed by the seal() method. Hence, we get a TypeError.

Notes:

  • By default, objects are extensible (new properties can be added to them). The sealing of objects makes properties on objects fixed and immutable. The values of present properties can still be changed as long as they are writable.
  • Object.isSealed() can be used to check if an object is sealed or not.
  • Attempt to convert data property to accessor or vice versa will fail silently or throw TypeError.

Also Read:

Did you find this article helpful?