Validation and Side Effects
Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 45 of 56.
Getters and setters can do more than just read and write properties - they can validate inputs and trigger side effects when values change.
Let's create a User class with validation:
class User {
constructor(name, age) {
this._name = name;
this._age = age;
}
get age() {
return this._age;
}
set age(value) {
// Validate age is a number and within reasonable range
if (typeof value !== 'number') {
throw new Error('Age must be a number');
}
if (value < 0 || value > 120) {
throw new Error('Age must be between 0 and 120');
}
this._age = value;
// Side effect: log when age changes
console.log(`Age updated to ${value}`);
}
}Now when we use the setter, validation happens automatically:
const user = new User('Alice', 25);
// This works
user.age = 30; // Logs: "Age updated to 30"
// This throws an error
user.age = -5; // Error: Age must be between 0 and 120
// This also throws an error
user.age = "thirty"; // Error: Age must be a numberValidation = Checking if a value is valid before storing it
Side Effects = Additional actions that happen when a property changes
Challenge
You're given a BankAccount class with a basic setter. Your task is to complete the balance setter.
Add to the setter:
- Validation: Check if
valueis not a number OR is less than 0 - if so,console.log("Invalid balance")and usereturnto exit the setter - Side Effect: After storing a valid value,
console.log(\`Balance updated to ${value}\`)
Cheat sheet
Getters and setters can validate inputs and trigger side effects when values change.
Validation checks if a value is valid before storing it:
set age(value) {
if (typeof value !== 'number') {
throw new Error('Age must be a number');
}
if (value < 0 || value > 120) {
throw new Error('Age must be between 0 and 120');
}
this._age = value;
}Side Effects are additional actions that happen when a property changes:
set age(value) {
// validation...
this._age = value;
// Side effect: log when age changes
console.log(`Age updated to ${value}`);
}Example usage:
const user = new User('Alice', 25);
user.age = 30; // Logs: "Age updated to 30"
user.age = -5; // Error: Age must be between 0 and 120Try it yourself
import { BankAccount } from './account.js';
// Test cases
const account = new BankAccount("Savings");
// Test 1: Valid balance
account.balance = 100;
console.log(account.balance);
// Test 2: Invalid balance (negative)
account.balance = -50;
console.log(account.balance);
// Test 3: Invalid balance (not a number)
account.balance = "abc";
console.log(account.balance);
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