liveBook · Manning

Object.defineProperty

As explained in JavaScript in Depth

A JavaScript standard library method that defines or redefines a property with explicit descriptor attributes.

A property can exist yet resist assignment, iteration, or deletion. Object.defineProperty() creates or redefines it through explicit descriptor attributes: writable controls value changes, enumerable controls visibility in for...in and Object.keys(), and configurable controls deletion and descriptor changes. section 5.2.3

A locked, visible serial number

Define serialNumber with writable: false, enumerable: true, and configurable: false. Deleting it fails, and a later Object.defineProperty() call cannot change its attributes, although the property remains directly readable. Strict mode throws on assignment to a non-writable property; sloppy mode silently fails. section 5.2.3

const drawer = {};
Object.defineProperty(drawer, 'serialNumber', {
  value: 'SN-12345',
  writable: false,  #A
  enumerable: true,  #B
  configurable: false,  #C
});
delete drawer.serialNumber;
console.log(drawer.serialNumber);  // #D
Object.defineProperty(drawer, 'serialNumber', {
  writable: true,  // #E
});

Inspect the interaction between non-writable and non-configurable attributes through deletion and attempted redefinition. section 5.2.3

How JavaScript in Depth covers it

How deep it goes
Explains descriptor flags, default differences, strictness effects, and accessor descriptors, stopping short of broader runtime internals.
Examples
Uses drawer contents, internal identifiers, serial numbers, object-literal defaults, and getter-setter properties.
What it assumes
Assumes objects, property access, assignment, deletion, loops, and strict versus sloppy mode while teaching descriptor attributes from their effects.
What you can do after
Apply it via Object.defineProperty() to create controlled data or accessor properties and predict assignment, iteration, and deletion outcomes.
How it connects
Connects property descriptors with object literals, Object.getOwnPropertyDescriptor(), Object.defineProperties(), accessors, and strict mode.

Also explained in

Compare how 3 books explain Object.defineProperty →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.