The get and set Keywords
Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 43 of 56.
Getters and setters are special methods that look like properties but are actually functions. They give you control over how properties are accessed and modified.
Let's create a simple Person class:
class Person {
constructor(firstName, lastName) {
this._firstName = firstName;
this._lastName = lastName;
}
// Getter for fullName
get fullName() {
return `${this._firstName} ${this._lastName}`;
}
// Setter for fullName
set fullName(value) {
const parts = value.split(' ');
this._firstName = parts[0];
this._lastName = parts[1];
}
}Now we can use these getters and setters like properties:
// Create a new Person
const person = new Person('John', 'Doe');
// Use the getter
console.log(person.fullName); // Output: John Doe
// Use the setter
person.fullName = 'Jane Smith';
// The setter has updated the internal properties
console.log(person.fullName); // Output: Jane SmithNotice that we don't call these methods with parentheses. They behave just like properties but execute code when accessed or modified.
Challenge
You're given a User class with an age property. Your task is to add a getter and setter for age that:
- Getter
<strong>get age()</strong>: returns the stored age - Setter
<strong>set age(newAge)</strong>: validates that age is between 0 and 120- If valid (0-120): store it in
this._age - If invalid: don't change it and log
"Invalid age!"
- If valid (0-120): store it in
Cheat sheet
Getters and setters are special methods that look like properties but execute code when accessed or modified.
Getter - use the get keyword to define a method that returns a value:
class Person {
constructor(firstName, lastName) {
this._firstName = firstName;
this._lastName = lastName;
}
get fullName() {
return `${this._firstName} ${this._lastName}`;
}
}Setter - use the set keyword to define a method that accepts a value:
class Person {
set fullName(value) {
const parts = value.split(' ');
this._firstName = parts[0];
this._lastName = parts[1];
}
}Usage - access getters and setters like properties (without parentheses):
const person = new Person('John', 'Doe');
// Using getter
console.log(person.fullName); // John Doe
// Using setter
person.fullName = 'Jane Smith';
console.log(person.fullName); // Jane SmithTry it yourself
import { User } from './user.js';
// Test code - don't modify
const user = new User("Alice", 25);
console.log(user.age); // Should output 25
user.age = 30;
console.log(user.age); // Should output 30
user.age = 150; // Should show "Invalid age!"
console.log(user.age); // Should still output 30 (unchanged)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Objects & The this Keyword
Quick Review: ObjectsAdding Methods to ObjectsUnderstanding the this KeywordConstructor FunctionsThe new KeywordRecap Challenge7 Inheritance & The extends Key
InheritanceThe "is-a" RelationshipThe extends KeywordThe super() MethodInheriting Properties&MethodsRecap Challenge2Organizing Code
What are Modules?Exporting with exportImporting with importDefault vs. Named Exports8Organizing OOP Code
Organize Classes into Modules11Project: A Shape Renderer
Setup: Shape Class & ExportCircle Class Inheritance9Static Methods & Properties
Class-Level vs. Instance-LevelStatic PropertiesStatic Utility MethodsRecap challenge12Getters & Setters
The get and set KeywordsComputed PropertiesValidation and Side EffectsRecap Challenge