Object

Object.defineProperty

Defines a new property directly on an object or modifies an existing property, and returns the object

Syntax

JavaScript
Object.defineProperty(obj, prop, descriptor)

Parameters

ParameterTypeDescription
objobjectThe object on which to define the property
propstring | symbolThe name of the property
descriptorPropertyDescriptorThe descriptor for the property

Return Value

The object that was passed to the function

Examples

Basic Usage
const obj: Record<string, unknown> = {};
Object.defineProperty(obj, 'name', {
  value: 'Alice',
  writable: false,
  enumerable: true,
});
console.log(obj.name); // 'Alice'
Practical Example
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); // 0
Advanced Usage
const obj: Record<string, unknown> = {};
Object.defineProperty(obj, 'id', {
  value: 42,
  writable: false,
  configurable: false,
});
// obj.id = 99; // TypeError in strict mode

Understanding 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.