My new favorite JavaScript feature is the Object.seal() method. I’ve used the Object.freeze() sometimes but, this is something new and I feel it can be really handy in many cases where we have a pre-defined object template to use and only want to change the values of its existing properties.
Sealing an Object with the seal() method
As the name says, we can seal a javascript object using the Object.seal() method. This means that once an object is sealed
1. We cannot add new properties to the object
2. Existing properties cannot be modified
3. But, the value of existing properties can be changed
How to seal an Object in JavaScript
const siteObject = {
name: "matrixread",
posts:100
};
Object.seal(siteObject);
// Object is sealed now
siteObject.posts = 200;
// We can modify existing properties
siteObject.author = "Abhiram Reddy"
// We cannot add a new property
delete siteObject.name;
// We cannot delete existing proprties
console.log(siteObject);
// Output
// { name: 'matrixread', posts: 200 }
Object.seal() vs Object.freeze()
Object.freeze() is almost the same as Object.seal() but when an object is frozen we cannot modify even the values of the properties. This means that once an object is frozen.
- We cannot add new properties to the object
- Existing properties cannot be modified
- The values of existing properties cannot be changed
const siteObject = {
name: "matrixread",
posts:100
};
Object.freeze(siteObject);
// Object is Frozen now
siteObject.posts = 200;
// We cannot modify existing properties
siteObject.author = "Abhiram Reddy"
// We cannot add a new property
delete siteObject.name;
// We cannot delete existing proprties
console.log(siteObject);
// Output
// { name: 'matrixread', posts: 100 }
As we can learn from the output that the Object remained the same, not even the existing property values can be changed once an object is frozen.
Reference
Object.seal() at MDN
Conclusion
I can’t wait to use the Object.seal() method in my code as it makes the whole object structure fixed and even prevents us from making changes by accident. What do you think?