JavaScript Object.seal(obj) method


The Object.seal(obj) method in JavaScript is used to seal an object, which means that it prevents new properties from being added to the object and marks all existing properties as non-configurable. However, it allows existing properties to be modified or deleted. This method is useful for ensuring that the structure of an object remains the same while still allowing changes to its values.

Syntax:

Object.seal(obj);

Parameters:

  • obj: The object you want to seal. This object is passed by reference.

Return Value:

  • The sealed object itself.

Key Features:

  • Preventing Additions: After an object is sealed, no new properties can be added to it.
  • Non-Configurable Properties: All existing properties become non-configurable. This means that you cannot change the descriptor of any property (e.g., making a property non-enumerable).
  • Modifiable Properties: Existing properties can still be modified (i.e., their values can be changed) and deleted, unless they are marked as non-writable.
  • Shallow Sealing: Like Object.freeze(), Object.seal() only affects the immediate properties of the object. If the object contains nested objects, those nested objects are not sealed automatically.

Example 1: Basic Usage

const obj = { name: 'Alice', age: 30 }; Object.seal(obj); obj.age = 31; // This will change the age property obj.gender = 'female'; // This will not add the gender property delete obj.name; // This will not delete the name property console.log(obj); // Output: { name: 'Alice', age: 31 }

In this example, after sealing the obj, the age property can still be modified, but new properties cannot be added and existing properties cannot be deleted.

Example 2: Checking if an Object is Sealed

You can check if an object is sealed using Object.isSealed():

const obj = { name: 'Bob' }; Object.seal(obj); console.log(Object.isSealed(obj)); // Output: true

In this case, Object.isSealed(obj) returns true because the object has been sealed.

Example 3: Sealing an Array

You can also use Object.seal() on arrays:

const arr = [1, 2, 3]; Object.seal(arr); arr.push(4); // This will add the value to the array console.log(arr); // Output: [1, 2, 3, 4] delete arr[0]; // This will delete the first element console.log(arr); // Output: [ , 2, 3, 4]

In this example, the array is sealed, so you can modify the values, but you cannot change the array structure in terms of property descriptors.

Summary:

  • Object.seal(obj) is a method that seals an object, making it non-extensible while allowing existing properties to be modified.
  • It prevents new properties from being added and marks all existing properties as non-configurable.
  • Understanding how to use Object.seal() is important for scenarios where you want to maintain the structure of an object while allowing for some level of flexibility in its property values.