Open In App

What is Object.defineProperty() in JavaScript?

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • object: The object on which to define or modify the property.
  • propertyKey: The name of the property to be defined or modified.
  • descriptor: An object that specifies the attributes of the property being defined or modified.

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.

Javascript




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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads