Learn more about the seal() method in JavaScript, which is used to restrict the modification of an object’s properties.

The seal() method, when called on an object, returns the same object. The object passed as an argument is mutated and becomes immutable. This means that new properties cannot be added to it, existing properties cannot be removed, but they can still be modified.

Here’s an example to demonstrate it:

const dog = {}
dog.breed = 'Siberian Husky'
Object.seal(dog)
dog.breed = 'Pug'
dog.name = 'Roger' // TypeError: Cannot add property name, object is not extensible

In this example, after calling seal() on the dog object, we try to modify the breed property, which is allowed. However, when trying to add the name property, it results in a TypeError because the object is no longer extensible.

The object passed as an argument is also returned by the seal() method, so dog is equivalent to myDog (they reference the same object).

The behavior of seal() is similar to Object.freeze(), but it does not make the properties non-writable. It only prevents the addition or removal of properties.

Similarly, seal() is comparable to Object.preventExtensions(), but it additionally disallows the removal of properties. Here’s an example to illustrate it:

const dog = {}
dog.breed = 'Siberian Husky'
dog.name = 'Roger'
Object.seal(dog)
delete dog.name // TypeError: Cannot delete property 'name' of #<Object>

In this case, attempting to delete the name property after sealing the object results in a TypeError.

By understanding the seal() method, you can effectively control the modification of an object’s properties, ensuring the desired level of immutability.