JavaScript Property Getters & Setters
JavaScript getters and setters allow you to define custom behavior when accessing or modifying object properties. They make it possible to control how a property is retrieved or updated.
š¹ Getters (get
)
A getter is a method that acts as a computed property. It is called when a property is accessed.
✅ Example:
✔ No function call needed (user.fullName
instead of user.fullName()
).
š¹ Setters (set
)
A setter allows custom logic when setting a property value.
✅ Example:
✔ When we assign a value to fullName
, the setter splits the string and updates firstName
and lastName
.
š¹ Using Getters & Setters with Object.defineProperty()
We can also define getters and setters using Object.defineProperty()
.
š¹ Getters & Setters with Classes
Getters and setters work seamlessly in classes.
š¹ Protecting Properties with Getters
Getters can be used to create read-only properties.
✔ No setter → The property cannot be modified.
šÆ Summary
✔ get
→ Allows computed property access.
✔ set
→ Allows custom logic when setting a property.
✔ Works with objects, Object.defineProperty()
, and classes.
✔ Use getters for read-only properties.
š Mastering getters and setters improves data control in JavaScript! Let me know if you need more examples. š