JS Tip of the Day: Preventing Extensions in Objects

Preventing Extensions in Objects
Level: Beginner

Objects are a collection of properties. Normally you can add new properties to them with dot (or bracket) syntax and the assignment operator.

let obj = {};
obj.prop = 'a new property';
console.log(obj.prop); // a new property

But you can also lock down an object and prevent new properties from being added by “preventing extensions” in that object. This can be done with the function Object.preventExtensions().

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

Preventing extensions does not prevent you from deleting properties, only adding them. It also doesn’t apply to inheritance so a new property could be added if inherited.

Once you prevent extensions in an object, you can’t go back. But you can check to see if an object has had its extensions prevented using Object.isExtensible().

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

More info: