protection

Object.preventExtensions

Prevents new properties from being added to an object, but existing properties can still be modified, deleted, or reconfigured. The weakest of the three protection levels.

Object.preventExtensions(obj)

Parameters

Parameter Purpose
obj The object to make non-extensible
returns The same (now non-extensible) object

Examples

const o = Object.preventExtensions({ a: 1 });
try { o.b = 2; } catch (e) {}
console.log(o.b);

Logs undefined — new property rejected

const o = Object.preventExtensions({ a: 1 });
o.a = 99;
delete o.a;
console.log(o.a);

Logs undefined — existing properties are still mutable and deletable

console.log(Object.isExtensible(Object.preventExtensions({})));

Logs false

const o = Object.preventExtensions({});
try { Object.setPrototypeOf(o, { p: 1 }); } catch (e) { console.log(e.name); }

Logs 'TypeError' — the prototype is also locked

Gotcha

Also prevents changing the prototype via setPrototypeOf. Weaker than seal (which additionally makes properties non-configurable) and freeze (which additionally makes data properties non-writable).

Related methods

← All JS Object methods · Array methods · Spread vs rest