creation

Object.defineProperty

Defines a new property directly on an object, or modifies an existing one, with fine-grained control over its descriptor. Returns the object.

Object.defineProperty(obj, prop, descriptor)

Parameters

Parameter Purpose
obj The target object
prop Property key (string or Symbol)
descriptor Data descriptor (value/writable) or accessor descriptor (get/set), plus enumerable/configurable

Examples

const o = {};
Object.defineProperty(o, 'x', { value: 1, enumerable: true });
console.log(o.x, Object.keys(o));

Logs 1 [ 'x' ] — enumerable was explicitly set

const o = {};
Object.defineProperty(o, 'x', { value: 1 });
console.log(o.x, Object.keys(o));

Logs 1 [] — defaults to non-enumerable, non-writable, non-configurable

const o = {};
Object.defineProperty(o, 'full', {
  get() { return 'Ada Lovelace'; }
});
console.log(o.full);

Logs 'Ada Lovelace' — accessor descriptor with a getter

const o = {};
Object.defineProperty(o, 'x', { value: 1 });
try { o.x = 2; } catch (e) {}
console.log(o.x);

Logs 1 — silently fails in sloppy mode, throws in strict mode

Gotcha

Descriptor booleans DEFAULT TO FALSE (writable/enumerable/configurable) — the opposite of plain assignment. Cannot mix data-descriptor keys (value/writable) with accessor keys (get/set) in the same call.

Related methods

← All JS Object methods · Array methods · Spread vs rest