Object.defineProperty
Defines a new property directly on an object or modifies an existing property, and returns the object
Syntax
Object.defineProperty(obj, prop, descriptor)Parameters
| Parameter | Type | Description |
|---|---|---|
| obj | object | The object on which to define the property |
| prop | string | symbol | The name of the property |
| descriptor | PropertyDescriptor | The descriptor for the property |
Return Value
The object that was passed to the function
Examples
const obj: Record<string, unknown> = {};
Object.defineProperty(obj, 'name', {
value: 'Alice',
writable: false,
enumerable: true,
});
console.log(obj.name); // 'Alice'const counter = { _count: 0 };
Object.defineProperty(counter, 'count', {
get() { return this._count; },
set(val) { this._count = Math.max(0, val); },
});
(counter as any).count = -5;
console.log((counter as any).count); // 0const obj: Record<string, unknown> = {};
Object.defineProperty(obj, 'id', {
value: 42,
writable: false,
configurable: false,
});
// obj.id = 99; // TypeError in strict modeUnderstanding Object.defineProperty
The Object.defineProperty method in JavaScript defines a new property directly on an object or modifies an existing property, and returns the object. It belongs to the Object object and is one of the most widely used methods for working with object values in modern JavaScript and TypeScript applications.
The method signature is Object.defineProperty(obj, prop, descriptor). It accepts 3 parameters: obj, prop, descriptor. When called, it returns the object that was passed to the function. Understanding when and how to use defineProperty() helps you write more expressive, readable code.
Common use cases for Object.defineProperty include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like object-defineproperties, object-getownpropertydescriptor, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for Object.defineProperty is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
More Object Methods
Other methods in the Object object
Related Tools
More Object Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.