The Object.seal()
method in JavaScript is a robust tool for controlling object modification. It allows you to seal an object, preventing new properties from being added to it while also marking all existing properties as non-configurable. Properties of a sealed object can still be changed as long as they are writable. This functionality is particularly useful in maintaining object integrity, avoiding accidental modifications or expansions after an object's initial creation and setup.
In this article, you will learn how to effectively use the Object.seal()
method to make objects non-extensible. Discover how to seal objects, check if an object is sealed, and understand the implications of sealing objects in your JavaScript projects.
Start with a simple object.
Apply the Object.seal()
function to restrict it.
const user = { name: "Alex", age: 30 };
Object.seal(user);
This code creaes an object user
and seals it using Object.seal()
. After sealing, you cannot add new properties to the user
object, nor can you remove existing ones.
Despite sealing, modify the values of existing writable properties.
user.age = 31;
console.log(user.age); // Outputs: 31
This example demonstrates modifying the age property of the sealed user
object. The change is allowed because the existing properties remain writable.
Try to add a new property to the sealed object and observe the result.
user.location = "New York";
console.log(user.location); // Outputs: undefined
Attempting to add a new property location
to the sealed user
object does not work, and accessing user.location
returns undefined
since the addition is ignored.
Verify whether an object has been sealed.
console.log(Object.isSealed(user)); // Outputs: true
The Object.isSealed()
method checks if the object user
is sealed, returning true
if it is sealed, and false
otherwise. This method is helpful for debugging and enforcing object integrity during runtime.
Object.seal()
when you want to lock an object's structure after its initial setup.The Object.seal()
method is a valuable tool for managing object mutability in JavaScript. By preventing extensions and making object properties non-configurable, you help ensure the stability and integrity of your objects throughout their lifecycle. Use Object.seal()
to maintain predictable object behavior, guard against inadvertent property additions or deletions, and uphold object structure as you develop and manage your JavaScript applications. Implementing these techniques secures your objects against modifications that could potentially disrupt your application’s state or behavior.