The Object.defineProperty function is utilized to create a new property directly on a specified object and subsequently returns that object. To modify the property attributes, Object.defineProperty can be employed. However, it is important to note that once a property is marked as non-configurable, it cannot be reverted to a configurable state, as the define property feature does not apply to properties that are non-configurable.
Syntax:
Object.defineProperty(obj, prop, descriptor)
Parameter
Obj : The Object on which to define the property.
Prop: The designation of a property that is intended to be established or altered.
Descriptor: The term used to identify the property that is either being established or altered.
Return:
This technique yields the object that was provided as an argument to the function.
Browser Support:
| Chrome | Yes |
|---|---|
Edge |
Yes |
| Firefox | 1.5 |
| Opera | Yes |
Example 1
const object1 = {};
Object.defineProperty(object1, 'property1', {
value: 22, } );
object1.property1;
// throws an error in strict mode
console.log(object1.property1);
Output:
Example 2
const object1 = {};
Object.defineProperty(object1, 'property1', {
value: 42,
value: 52,
value: 542,
});
object1.property1 = 177;
// throws an error in strict mode
console.log(object1.property1);
Output:
Example 3
const object1 = {};
Object.defineProperty(object1, 'property1', {
value: 2,
value: 4,
value: 4+13,
});
object1.property1 ;
console.log(object1.property1);
Output: