Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Getters and setters are special methods that look like properties but run code when you read or write them. Like a gatekeeper that controls access!
Use get before a method to make it a getter
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// Getter - access like a property
get fullName() {
return this.firstName + ' ' + this.lastName;
}
}
const person = new Person('John', 'Doe');
console.log(person.fullName); // 'John Doe'
// No () needed! Looks like a propertyComputed properties with get
Use set to validate values before storing
class Person {
constructor(age) {
this._age = age; // underscore = private by convention
}
get age() {
return this._age;
}
// Setter - validate before setting
set age(value) {
if (value < 0 || value > 150) {
console.log('Invalid age!');
return;
}
this._age = value;
}
}
const person = new Person(25);
person.age = 30; // ✓ Valid
person.age = -5; // ✗ 'Invalid age!'
person.age = 200; // ✗ 'Invalid age!'Control what values are accepted
Combine getter and setter for complete control
class Product {
constructor(name, price) {
this.name = name;
this._price = price;
}
get price() {
return '$' + this._price.toFixed(2);
}
set price(value) {
if (value < 0) {
console.log('Price cannot be negative!');
return;
}
this._price = value;
}
}
const product = new Product('Laptop', 999.99);
console.log(product.price); // '$999.99' (formatted)
product.price = 1299.5;
console.log(product.price); // '$1299.50'
product.price = -50; // 'Price cannot be negative!'Real-world property control
You can use getters/setters in regular object literals
const person = {
firstName: 'John',
lastName: 'Doe',
get fullName() {
return this.firstName + ' ' + this.lastName;
},
set fullName(name) {
const [first, last] = name.split(' ');
this.firstName = first;
this.lastName = last;
}
};
console.log(person.fullName); // 'John Doe'
person.fullName = 'Jane Smith';
console.log(person.firstName); // 'Jane'
console.log(person.lastName); // 'Smith'Use in plain objects
_age)get fullName() - combine firstName + lastNameget price() - return formatted string like "$99.99"set age(value) - check if age is valid before settingget password() - return masked versionset fahrenheit() - convert to celsius internallyperson.getFullName(), you write person.fullName - much nicer!