JS: Reflect .preventExtensions

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2015)

Reflect.preventExtensions(obj)
  • Make object not extensible.
  • Return true if success, else false.
  • If arg is not an object, throw TypeError.
const jj = {};
console.assert(Reflect.isExtensible(jj));
Reflect.preventExtensions(jj);
console.assert(Reflect.isExtensible(jj) === false);

Non-extensible object, cannot revert, property can still be deleted, parent object may add properties

// property can still be deleted for non-extensible object
const jj = { dog: 3 };
Reflect.preventExtensions(jj);
console.assert(Object.hasOwn(jj, "dog"));
Reflect.deleteProperty(jj, "dog");
console.assert(Object.hasOwn(jj, "dog") === false);

[see Property Attributes]

Reflect.preventExtensions does not change property descriptor.

/* show Reflect.preventExtensions() does not change property descriptor. */

const jj = { dog: 3 };

console.assert(Reflect.isExtensible(jj));

const xdesc = Reflect.getOwnPropertyDescriptor(jj, "dog");

console.assert(xdesc.writable);
console.assert(xdesc.configurable);

Reflect.preventExtensions(jj);

console.assert(Reflect.isExtensible(jj) === false);

console.assert(xdesc.writable);
console.assert(xdesc.configurable);