JS: Object.freeze

JS: Object.freeze

Object.freeze(obj)

  1. Set the object's “extensible” attribute to false. (cannot add properties)
  2. Set ALL of the object's own property's “configurable” attributes to false. (cannot delete properties)
  3. Set ALL of the object's own property's “writable” attributes to false. (cannot change property values)

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

[see JS: Prevent Adding Property]

// freeze object

const oo = {k1:1, k2:2};

console.log(Object.getOwnPropertyDescriptor(oo, "k1"));
// { value: 1, writable: true, enumerable: true, configurable: true }

Object.freeze(oo);

console.log(Object.getOwnPropertyDescriptor(oo, "k1"));

// { value: 1,
//   writable: false,
//   enumerable: true,
//   configurable: false }

console.log(Object.getOwnPropertyDescriptor(oo, "k2"));
// { value: 2,
//   writable: false,
//   enumerable: true,
//   configurable: false }

console.log(Object.isExtensible(oo));
// false

Reference

ECMAScript® 2016 Language Specification#sec-object.freeze

Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon