Object.preventExtension vs Object.seal() in JavaScript
When working with JavaScript objects, you might come across the methods Object.preventExtension()
and Object.seal()
. These methods are used to define the behavior of an object with regards to its extensibility and mutability. Let’s take a closer look at each one.
Object.preventExtension()
The Object.preventExtension()
method is used to prevent any new properties from being added to an object. Once this method is called, the object becomes non-extensible, meaning that you cannot add new properties to it. However, you can still modify and delete existing properties.
Here’s an example:
let person = {name: 'John', age: 30};
Object.preventExtensions(person);
person.gender = 'male'; // This will throw an error
Object.seal()
The Object.seal()
method goes a step further than Object.preventExtension()
. It not only prevents new properties from being added, but it also prevents existing properties from being deleted or configured. In other words, once an object is sealed, its properties become immutable.
Here’s an example:
let car = {brand: 'Toyota', model: 'Camry'};
Object.seal(car);
car.model = 'Corolla'; // This is allowed
delete car.brand; // This will throw an error
Conclusion
In summary, Object.preventExtension()
is used to prevent the addition of new properties to an object, while Object.seal()
takes it a step further by making the object’s properties immutable. These methods can be useful when you want to control the mutability and extensibility of your objects in JavaScript.