Skip to content

Sealing an object

Sealing Objects with Object.seal()

The Object.seal() method allows you to seal an object, preventing the addition or deletion of properties while still allowing property values to be changed.

const user = {
name: 'John',
age: 30,
// Attempt to add a new property (won't work) = 'USA';
// Attempt to delete a property (won't work)
delete user.age;
// Changing an existing property value (will work) = 'Alice';

Use Cases

Object.seal() is useful when you want to restrict modifications to an object but still allow for property value changes. For example, consider a user profile object:

const userProfile = {
username: 'jsmith',
email: '',
isAdmin: false,
// Attempting to add a new property or delete a property won't work.
// However, you can change the values of existing properties.

By sealing the userProfile object, you ensure that the structure remains constant, but you can update user details as needed.