Create a non-writable property
Expose a read-only public value while preventing reassignment.
JavaScript · Function
Defines or modifies an object's own property with a descriptor, controlling its value, accessors, and property flags. On success, it returns the original object.
Object.defineProperty() adds or updates an own property using a descriptor. The descriptor can control a data property's value, writability, enumerability, and configurability, or define accessor functions with get and set; omitted attributes default to false.
Object.defineProperty(obj, prop, descriptor)| Name | Type | Description |
|---|---|---|
obj | Object | The object on which to define the property. |
prop | string | Symbol | A string or Symbol specifying the property key to define or modify. |
descriptor | Object | The descriptor specifying the property's data or accessor attributes. |
The object passed as obj, with the specified property added or modified.
const user = {};
Object.defineProperty(user, "id", {
value: 42,
writable: false,
enumerable: true,
configurable: true,
});
console.log(user.id); // 42
console.log(Object.keys(user)); // ["id"]Defines an own data property whose value can be read and enumerated but not reassigned.
Expose a read-only public value while preventing reassignment.
Hide implementation details from Object.keys() and for...in.
Compute values dynamically or validate assignments.
Add or revise properties with explicit descriptor behavior.
It defines or modifies an own property on the supplied object and returns that same object. The property behavior comes from the descriptor argument.
Follow-up: How does it differ from Reflect.defineProperty()? Reflect.defineProperty() returns a Boolean success status, whereas Object.defineProperty() returns the object on success and throws a TypeError on failure.
A data descriptor uses value and writable; an accessor descriptor uses get and set. A descriptor must not combine data and accessor fields.
Follow-up: What happens when a descriptor omits configurable or enumerable? Those attributes default to false for a property created by this method.
The method defines a property through the object's [[DefineOwnProperty]] internal method rather than [[Set]]. Consequently, it does not invoke a setter merely because the property already exists.
Follow-up: Why might a proxy still observe the operation? A proxy can intercept the corresponding operation through its handler.defineProperty() trap.
Object.defineProperties()Object.getOwnPropertyDescriptor()Reflect.defineProperty()Proxyhandler.defineProperty()