Property Flags & Descriptors in JavaScript
In JavaScript, property descriptors give us fine control over object properties' behavior. They let us define attributes like writability, enumerability, and configurability.
š¹ Property Descriptors
Every property in JavaScript has a descriptor with default values:
✅ Output:
✔ By default, properties are writable, enumerable, and configurable.
š¹ Modifying Property Attributes
We can change these attributes using Object.defineProperty()
.
1️⃣ writable
- Controls Modification
If writable: false
, the property cannot be changed.
2️⃣ enumerable
- Controls Visibility in Loops
If enumerable: false
, the property won’t appear in loops.
✔ age
won’t show in Object.keys()
, for...in
, or JSON.stringify()
.
3️⃣ configurable
- Prevents Further Changes
If configurable: false
, we can’t delete or modify the descriptor.
š¹ Multiple Property Descriptors
Use Object.defineProperties()
to modify multiple properties at once:
š¹ Getters & Setters with Descriptors
We can define getter and setter methods instead of value
:
✔ Getters compute values, and setters modify them.
šÆ Summary
✔ writable: false
→ Prevents changes to a property.
✔ enumerable: false
→ Hides the property from loops.
✔ configurable: false
→ Prevents deletion/modification.
✔ Use Object.defineProperty()
to set descriptors.
✔ Getters & Setters allow computed properties.
š Mastering property descriptors gives you full control over object properties! Let me know if you need more examples. š