JS Tip of the Day: Sealing Objects

Sealing Objects
Level: Beginner

Just like you can prevent extensions in objects, you can also seal them. When an object is sealed, extensions are prevented and existing properties are set to non-configurable. Sealing is achieved with Object.seal().

let obj = { existing: true };
obj.prop = 'a new property'; // TypeError in strict mode
console.log(obj.prop); // undefined
delete obj.existing; // TypeError in strict mode
console.log(obj.existing); // true

Sealing an object locks the properties of an object in place so new ones can’t be added and existing ones can’t be removed. As with preventing extensions, it doesn’t apply to inheritance so a new property could be added (or removed) if inherited.

Once you seal an object, you can’t go back. But you can check to see if an object has been sealed using Object.isSealed().

let obj = {};
console.log(Object.isSealed(obj)); // false
console.log(Object.isSealed(obj)); // true

More info: