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
Object.defineProperties
Defines multiple new or modified properties on an object by supplying a descriptors map. The batch-form counterpart of Object.defineProperty.
Object.getOwnPropertyDescriptor
Returns the property descriptor for an own property on the given object, or undefined if the property does not exist. Descriptors describe writability, enumerability, configurability, and getters/setters.
Object.create
Creates a new object with the specified prototype and optional property descriptors. Pass null to create an object with no prototype at all.
Object.fromEntries
Transforms a list of key-value pairs into an object — the inverse of Object.entries. Introduced in ES2019 and accepts any iterable of [key, value] pairs, including Map.
Object.assign
Copies all enumerable own properties from one or more source objects to a target object, then returns the modified target. Performs a shallow merge, invoking source getters and target setters.