Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Object.defineProperties: several descriptors at once

Object.defineProperties defines several properties with full descriptors after collecting and validating the whole descriptor map.

Version: ECMAScript 5 onward; example target: Node.js 24.22.2

Syntax

Object.defineProperties(obj, properties)

Object.defineProperties(obj, properties) requires obj to be an object; it does not box primitives. properties undergoes ToObject, so null and undefined throw TypeError. The method snapshots the map’s own string and symbol keys, then includes only those whose current own descriptor is enumerable.

It first gets every selected value and converts it with ToPropertyDescriptor; only after all descriptors have been collected successfully does it begin defining properties on the target. An invalid descriptor or a throwing getter in this first phase therefore leaves the target unchanged. The definition phase itself is sequential, not transactional: if a later definition is incompatible, earlier ones may already remain.

The method returns the same obj and has existed since ECMAScript 5. When a new property is created, omitted writable, enumerable, and configurable become false, while omitted value, get, and set become undefined; when an existing property is updated, omitted fields remain unchanged. value/writable cannot be mixed with get/set, and an accessor must be callable or undefined. Getters and Proxy traps on the map or target can execute code and throw TypeError or their own exceptions.

Examples

const token = Symbol("token");
const target = {};
Object.defineProperties(target, {
  visible: { value: 3, enumerable: true },
  doubled: { get() { return this.visible * 2; }, enumerable: true },
  [token]: { value: "ok" }
});
console.log(Object.keys(target).join(","), target.doubled, target[token]);
console.log(Object.getOwnPropertyDescriptor(target, "visible").writable);
const untouched = {};
try {
  Object.defineProperties(untouched, {
    first: { value: 1 },
    bad: { get: 1 }
  });
} catch (error) { console.log(error.name, Object.hasOwn(untouched, "first")); }
const partial = {};
Object.defineProperty(partial, "locked", { value: 1 });
try {
  Object.defineProperties(partial, {
    added: { value: 2 },
    locked: { value: 3 }
  });
} catch (error) { console.log(error.name, partial.added, partial.locked); }

Result

visible,doubled 6 ok
false
TypeError false
TypeError 2 1

The example shows symbols, restrictive defaults, preflight validation, and a partial change during definition.

Sources