74. Getters and Setters
Getters and setters are special methods that allow you to define properties that look like regular data fields but execute code when they are accessed or modified. This is useful for validation or calculated values.
1. Getter (get)
A getter method is executed when the property is read.
javascript class Circle { constructor(radius) { this._radius = radius; // Use _ convention for internal properties }
get diameter() {
return this._radius * 2;
}
}
const smallCircle = new Circle(5); // Accessing diameter looks like accessing a property, not calling a function console.log(smallCircle.diameter); // Output: 10
2. Setter (set)
A setter method is executed when the property is assigned a value. This is where you can add validation logic.
javascript set diameter(newDiameter) { if (newDiameter < 0) { throw new Error('Diameter cannot be negative.'); } this._radius = newDiameter / 2; } }
smallCircle.diameter = 20; // Triggers the setter method console.log(smallCircle._radius); // 10 // smallCircle.diameter = -5; // Throws an Error