Object.defineProperty()
Object.defineProperty(obj, prop, descriptor) Returns:
Object (the modified object) · Updated March 16, 2026 · Object Methods object property descriptor oop
Object.defineProperty() lets you add or modify a property on an object with fine-grained control over its behavior. Unlike simple assignment, it lets you define whether the property is writable, enumerable, or configurable — the three attribute flags that govern property behavior.
Syntax
Object.defineProperty(obj, prop, descriptor)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
obj | Object | — | The object on which to define the property |
prop | String | — | The property name (string or symbol) |
descriptor | Object | — | The property descriptor object |
The descriptor object can include:
| Attribute | Type | Default | Description |
|---|---|---|---|
value | any | undefined | The property’s value |
writable | Boolean | false | If true, the value can be changed |
enumerable | Boolean | false | If true, the property appears in for...in loops |
configurable | Boolean | false | If true, the property can be deleted or modified |
Examples
Adding a read-only property
const user = {};
Object.defineProperty(user, 'name', {
value: 'Alice',
writable: false,
enumerable: true,
configurable: false
});
console.log(user.name);
// 'Alice'
user.name = 'Bob';
console.log(user.name);
// 'Alice' — unchanged because writable is false
Creating a getter-only property
const product = {
_price: 99
};
Object.defineProperty(product, 'price', {
get() {
return this._price;
},
enumerable: true,
configurable: true
});
console.log(product.price);
// 99
product.price = 50;
console.log(product.price);
// 99 — setter not defined, assignment ignored
Making a property invisible to loops
const config = {
apiKey: 'secret123'
};
Object.defineProperty(config, 'apiKey', {
enumerable: false
});
console.log(Object.keys(config));
// [Global_Objects::eval] — apiKey is hidden
for (const key in config) {
console.log(key);
}
// (nothing) — property is not enumerable
Common Patterns
Factory pattern for private data: Use closures with Object.defineProperty() to create true private fields before ES6 classes existed.
Immutability: Combine Object.defineProperty() with Object.freeze() to create fully immutable objects.
Reactive data: Define getters and setters to trigger updates when a property changes — the basis for many reactivity systems.
See Also
- Object.freeze() — make an object entirely immutable
- Object.keys() — Get array of object keys