JavaScript: Object.freeze

By Xah Lee. Date: . Last updated: .
Object.freeze(obj)

Freezing a object makes it impossible to {add, delete, change} properties.

  • Make the object not extensible.
  • Set ALL of the object's own property's configurable attributes to false.
  • Set ALL of the object's own property's writable attributes to false.
// freeze object

const jj = { p1: 1, p2: 2 };

const xkeys = Reflect.ownKeys(jj);

// all properties are writable and configurable
console.log(
  xkeys.every((x) => {
    const xdesc = Reflect.getOwnPropertyDescriptor(jj, x);
    return xdesc.writable && xdesc.configurable;
  }),
);

// freeze it
Object.freeze(jj);

// now all properties are not writable and not configurable
console.log(
  xkeys.every((x) => {
    const xdesc = Reflect.getOwnPropertyDescriptor(jj, x);
    return !xdesc.writable && !xdesc.configurable;
  }),
);

// is not extensible
console.log(Object.isExtensible(jj) === false);

JavaScript Prevent Change Property

BUY ΣJS JavaScript in Depth