The Object defineProperty() method is used to define a new property on an object or modify an existing one and returns the object.
Syntax
Object.defineProperty(obj, prop, descriptor)
Parameters
- obj: The object on which to define the property.
- prop: The name or Symbol of the property to be defined or modified.
- descriptor: The descriptor for the property being defined or modified. This can include: value, writable, configurable, enumerable, get and set.
Return value
Returns object that was passed to the function.
Visual Representation
Example 1: How to Use Object.defineProperty() Method
let marvel = {}
Object.defineProperty(marvel, 'ironman', {
value: 'Tony Stark'
})
console.log(marvel.ironman)
Output
Tony Stark
Example 2: Passing enumerable to true
The enumerable is true if and only if this property shows up during the enumeration of the properties on the corresponding object.
let marvel = {}
Object.defineProperty(marvel, 'ironman', {
value: 'Tony Stark',
enumerable: true,
})
console.log(marvel.ironman)
console.log(marvel)
Output
Tony Stark
{ ironman: 'Tony Stark' }
When you set enumerable to false, the property ironman will not be visible in the object’s enumeration.
let marvel = {}
Object.defineProperty(marvel, 'ironman', {
value: 'Tony Stark',
enumerable: false,
})
console.log(marvel.ironman)
console.log(marvel)
Output
Tony Stark
{}
Example 3: Modifying an existing property
let marvel = {}
Object.defineProperty(marvel, 'ironman', {
value: 'Tony Stark',
writable: false,
})
console.log(marvel.ironman)
marvel.ironman = 'RDJ' // No effect because writable is false
console.log(marvel.ironman)
Output
Tony Stark
{}
Example 4: Using Access Descriptors
let obj = {};
// Define a property with access descriptors
Object.defineProperty(obj, "serialNumber", {
// Getter logs and returns the held value
get: function() {
console.log("Retrieving the Value...");
return valueHolder;
},
// Setter logs and stores the new value
set: function(newValue) {
console.log("Assigning a New Value...");
valueHolder = newValue;
},
enumerable: true,
configurable: true
});
// Set and then get the serialNumber property
obj.serialNumber = 17;
console.log("Serial Number:", obj.serialNumber);
Output
Assigning a New Value...
Retrieving the Value...
Serial Number: 17
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.