Object.defineProperty() creates the new property as described when a specified property doesn’t exist in an object. Fields may be omitted from a descriptor, and default values for those fields are inputted.
Normal property addition through assignment creates the properties that show up during a property enumeration (for…in loop or Object.keys() method), whose values may be changed and deleted.
Javascript Object defineProperty
JavaScript Object.defineProperty() is a static method that directly defines the new property on the object or modifies an existing property.
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.
Example
// app.js const marvel = {} Object.defineProperty(marvel, 'ironman', { value: 'Tony Stark' }) console.log(marvel.ironman)
See the output.
We defined the property on a marvel object.
Let’s print the object.
// app.js const marvel = {} Object.defineProperty(marvel, 'ironman', { value: 'Tony Stark' }) console.log(marvel)
See the output.
The object is empty, but when you try to print the property, it gives its value. So we can use the enumerable property.
The enumerable is true if and only if this property shows up during the enumeration of the properties on the corresponding object.
Add an enumerable property to true while defining a property on an object.
// app.js const marvel = {} Object.defineProperty(marvel, 'ironman', { value: 'Tony Stark', enumerable: true, }) console.log(marvel.ironman) console.log(marvel)
See the output.
Modifying a property
Let’s change the existing property.
// app.js const marvel = {} Object.defineProperty(marvel, 'ironman', { value: 'Tony Stark', enumerable: true, writable: true, configurable: true }) console.log(marvel.ironman) marvel.ironman = 'RDJ' console.log(marvel.ironman) console.log(marvel)
See the output.
That’s it.