Open In App

What is Object.defineProperty() in JavaScript?

In JavaScript, Object.defineProperty() is a method used to define a new property directly on an object or modify an existing property on an object. It provides fine-grained control over property attributes such as value, writable, enumerable, and configurable.

Syntax:

Object.defineProperty(object, propertyKey, descriptor)

Parameters:

Example: Here, Object.defineProperty() is used to define a new property named 'name' on the obj object with the value 'John'. The descriptor object specifies that the property is writable, enumerable, and configurable.




const obj = {};
 
// Define a new property 'name' with value 'John'
Object.defineProperty(obj, 'name', {
  value: 'GFG',
  writable: true,
  enumerable: true,
  configurable: true
});
 
console.log(obj.name);

Output
GFG

Article Tags :