Object.defineProperty
Defines a property with exact settings: read-only, hidden, with a getter.
Available since: ES5
Syntax
Object.defineProperty(obj, key, descriptor)Parameters
| Parameter | Type | Description |
|---|---|---|
| obj | object | The object on which the property is defined. |
| key | string | symbol | The property name. |
| descriptor | object | The property description: value, writable, enumerable, configurable, or get and set. |
Return value
objectThe same object.
Examples
A read-only property:
const user = {};
Object.defineProperty(user, 'id', { value: 42, writable: false });
user.id = 7;
console.log(user.id);Output:
42A hidden property does not appear in Object.keys and JSON:
const user = { name: 'Anna' };
Object.defineProperty(user, 'password', { value: 'secret', enumerable: false });
console.log(Object.keys(user));
console.log(JSON.stringify(user));
console.log(user.password);Output:
[
"name"
]
{"name":"Anna"}
secretNotes
By default every flag (writable, enumerable, configurable) is false for properties created this way. For ordinary properties created by assignment they are true.
See also
- Object.freeze — Prevents any changes to an object.
- get / set — Properties backed by functions: reading calls get, writing calls set.
- Object.keys — Returns an array of an object's property names.
In the tutorial
- Immutability — Mutable and immutable data in JavaScript: object references, copying with spread, the toSorted and with methods, Object.freeze and structuredClone.