JS: Object extensible, seal, freeze

By Xah Lee. Date: . Last updated: .

Object can be extensible or not

An object may be made non-extensible, meaning, you cannot add properties to it.

often used together with Property Attributes configurable and writable. to control if property can be added, deleted, or value changed.

Parent object may be extensible

🛑 warning: if a object is not extensible, but its parent may be, so people can add properties to the parent object, and your object may still get unexpected properties, because property lookup goes thru Prototype Chain.

Prevent adding properties

Prevent {add, delete} properties

Prevent {add, delete, change} properties

What objects are extensible by default

// user defined objects are all extensible
[
 { cat: 3 },
 [3, 4],
 function f() {
  return 3;
 },
 new Date(),
].forEach((x) => {
 console.assert(Reflect.isExtensible(x));
});

// standard objects are all extensible
// here we only verify some
[
 Object,
 Object.prototype,
 Array,
 Array.prototype,
 Function,
 String,
 Date,
 RegExp,
].forEach((x) => {
 console.assert(Reflect.isExtensible(x));
});