CKTIS / JavaScript
Object.defineProperty: a precise property descriptor
Object.defineProperty defines or changes one own property using an explicit data or accessor descriptor.
Version: ECMAScript 5 onward; example target: Node.js 24.22.2
Syntax
Object.defineProperty(obj, key, descriptor)Object.defineProperty(obj, key, descriptor) requires an actual object as obj; primitives are not boxed. key undergoes ToPropertyKey, so it becomes a string or symbol. descriptor is read by ToPropertyDescriptor, and the method returns the same target object.
A data descriptor uses value and writable, while an accessor descriptor uses get and set; combining fields from both kinds throws TypeError. When a new property is created, missing writable, enumerable, and configurable default to false, while missing value, get, and set mean undefined; when an existing property is updated, omitted fields leave its current attributes unchanged. A getter or setter must be callable or undefined.
The method has existed since ECMAScript 5. DefinePropertyOrThrow throws TypeError when adding a new property to a non-extensible object, when a change violates a non-configurable property’s rules, or when a Proxy breaks invariants. A compatible redefinition of an existing property can still succeed on a non-extensible object. Unlike assignment, it controls attributes without invoking an inherited setter, although reading descriptor fields and Proxy traps can execute code and throw.
Examples
const account = {};
const same = Object.defineProperty(account, "balance", {
value: 10, writable: false, enumerable: true, configurable: false
});
let reads = 0;
Object.defineProperty(account, "label", {
get() { return `#${++reads}`; }, configurable: true
});
console.log(same === account, Object.keys(account).join(","));
console.log(account.balance, account.label, account.label);
const balance = Object.getOwnPropertyDescriptor(account, "balance");
const label = Object.getOwnPropertyDescriptor(account, "label");
console.log(balance.writable, balance.configurable, label.set);
try { Object.defineProperty(account, "balance", { value: 11 }); }
catch (error) { console.log(error.name, account.balance); }
try { Object.defineProperty({}, "x", { value: 1, get() {} }); }
catch (error) { console.log(error.name); }Result
true balance 10 #1 #2 false false undefined TypeError 10 TypeError
The example defines a data property and getter, inspects attributes, and exercises two TypeError cases.