JavaScript Lock property description


Example

5

A property's descriptor can be locked so no changes can be made to it. It will still be possible to use the property normally, assigning and retrieving the value from it, but any attempt to redefine it will throw an exception.

The configurable property of the property descriptor is used to disallow any further changes on the descriptor.

var obj = {};

// Define 'foo' as read only and lock it
Object.defineProperty(obj, "foo", { 
    value: "original value", 
    writable: false, 
    configurable: false
});
 
Object.defineProperty(obj, "foo", {writable: true});

This error will be thrown:

TypeError: Cannot redefine property: foo

And the property will still be read only.

obj.foo = "new value";
console.log(foo);

Console output

original value