JavaScript Object.defineProperty() Method
The Object.defineProperty() static method adds or changes a property with precise control over whether it can be changed, deleted or listed.
Description
The Object.defineProperty() static method defines a property with a descriptor that controls its behavior. writable: false makes it read-only, enumerable: false hides it from Object.keys() and for...in, and configurable: false stops it from being deleted or redefined. Alternatively, get and set functions create a computed property.
All three flags default to false when you use defineProperty(), unlike normal assignment where they are true.
It's how libraries create read-only constants, hidden helper properties and computed properties on existing objects. To define several properties at once, use Object.defineProperties(), and to read a property's current settings, Object.getOwnPropertyDescriptor(). In class bodies, get and set syntax and private fields usually cover the same needs more readably.
Syntax
Object.defineProperty(obj, prop, descriptor)Parameters
- objThe object to work with.
- propThe name or symbol of the property.
- descriptorAn object with
value,writable,enumerableandconfigurable, orgetandsetfunctions.
Return Value
The object that was passed in.
Exceptions
- TypeErrorThrown if the property can't be defined, for example because it is non-configurable.
Example
Browser Support
The following information will show you the current browser support for the Object.defineProperty() method. Hover over a browser icon to see the version that first introduced support for this method.
Desktop





Tablets & Mobile





