0
0
JavascriptHow-ToBeginner · 4 min read

How to Use Object.defineProperty in JavaScript: Syntax and Examples

Use Object.defineProperty to add or change a property on an object with detailed control over its attributes like writable, enumerable, and configurable. It takes the object, property name, and a descriptor object to define how the property behaves.
📐

Syntax

The Object.defineProperty method has three parts:

  • object: The object to which you want to add or modify a property.
  • property: The name of the property as a string.
  • descriptor: An object that describes the property’s behavior, such as its value and whether it can be changed or listed.
javascript
Object.defineProperty(object, property, descriptor);
💻

Example

This example shows how to add a new property name to an empty object with a fixed value that cannot be changed or deleted.

javascript
const person = {};
Object.defineProperty(person, 'name', {
  value: 'Alice',
  writable: false,
  enumerable: true,
  configurable: false
});

console.log(person.name); // Outputs the value
person.name = 'Bob'; // Attempt to change the value
console.log(person.name); // Still 'Alice' because writable is false

for (const key in person) {
  console.log(key); // 'name' because enumerable is true
}
Output
Alice Alice name
⚠️

Common Pitfalls

Common mistakes include forgetting to set writable to true if you want to change the property later, or setting enumerable to false which hides the property in loops. Also, if configurable is false, you cannot delete or redefine the property later.

Another pitfall is confusing data descriptors (with value) and accessor descriptors (with get and set functions).

javascript
const obj = {};

// Wrong: Trying to change a non-writable property
Object.defineProperty(obj, 'fixed', {
  value: 10,
  writable: false
});
obj.fixed = 20; // This will not change the value

// Right: Make it writable if you want to change it
Object.defineProperty(obj, 'changeable', {
  value: 5,
  writable: true
});
obj.changeable = 15; // This changes the value

console.log(obj.fixed); // 10
console.log(obj.changeable); // 15
Output
10 15
📊

Quick Reference

PropertyDescriptionDefault Value
valueThe value of the propertyundefined
writableIf true, the property value can be changedfalse
enumerableIf true, the property shows up in loopsfalse
configurableIf true, the property can be deleted or changedfalse
getA function to get the property valueundefined
setA function to set the property valueundefined

Key Takeaways

Use Object.defineProperty to precisely control property behavior on objects.
Set writable, enumerable, and configurable to control mutability and visibility.
Accessor properties use get and set functions instead of value and writable.
Properties default to non-writable, non-enumerable, and non-configurable if not specified.
Trying to change a non-writable or non-configurable property will silently fail or throw in strict mode.