Problem Statement
What are getters and setters in JavaScript classes?
Explanation
Getters and setters are special methods that look like properties but execute code when accessed or assigned.
Getters use the get keyword and are called when you read a property. They must return a value.
Setters use the set keyword and are called when you assign to a property. They receive the new value as a parameter.
They allow computed properties and validation without exposing the implementation.
Getters and setters make APIs cleaner by hiding internal logic.
They are commonly used for data validation, computed properties, and encapsulation.
Code Solution
SolutionRead Only
// Getters and setters in class
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// Getter - acts like property
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
// Setter - acts like property assignment
set fullName(value) {
const parts = value.split(' ');
this.firstName = parts[0];
this.lastName = parts[1];
}
get age() {
return this._age;
}
set age(value) {
if (value < 0) {
throw new Error('Age cannot be negative');
}
this._age = value;
}
}
const john = new Person('John', 'Doe');
// Use getter like a property (no parentheses)
console.log(john.fullName); // 'John Doe'
// Use setter like property assignment
john.fullName = 'Jane Smith';
console.log(john.firstName); // 'Jane'
console.log(john.lastName); // 'Smith'
// Validation with setter
john.age = 30; // Works
console.log(john.age); // 30
// john.age = -5; // Error: Age cannot be negative
// Getters and setters in object literals
const circle = {
_radius: 5,
get radius() {
return this._radius;
},
set radius(value) {
if (value <= 0) {
throw new Error('Radius must be positive');
}
this._radius = value;
},
get area() {
return Math.PI * this._radius ** 2;
},
get circumference() {
return 2 * Math.PI * this._radius;
}
};
console.log(circle.radius); // 5
console.log(circle.area); // 78.53...
circle.radius = 10;
console.log(circle.area); // 314.15... (computed automatically)
// Private-like properties
class BankAccount {
constructor(balance) {
this._balance = balance; // Convention: _ means private
}
get balance() {
return this._balance;
}
set balance(value) {
throw new Error('Cannot set balance directly');
}
deposit(amount) {
this._balance += amount;
}
}
const account = new BankAccount(1000);
console.log(account.balance); // 1000
// account.balance = 5000; // Error!