Getters, Setters & Static Methods
Getters and setters let you control how properties are accessed and modified — adding validation, formatting, or computed values. Static methods belong to the class itself, not instances.
Getters, Setters, Static
- get — Access computed value like a property: user.fullName (no parentheses)
- set — Validate or transform on assignment: user.age = 150 → throws error
- Private fields (#) — class { #password; } — truly private, can't be accessed outside
- static — Methods on the class, not instances: User.create('Alice'). Factory methods, utilities
Getters, Setters, Static Code
class User {
#password; // private field
constructor(firstName, lastName, password) {
this.firstName = firstName;
this.lastName = lastName;
this.#password = password;
User.count++;
}
// Getter — access like property
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
// Setter — with validation
set age(value) {
if (value < 0 || value > 150) {
throw new Error("Invalid age!");
}
this._age = value;
}
get age() {
return this._age || "Not set";
}
// Static — belongs to class, not instances
static count = 0;
static create(name) {
const [first, last] = name.split(" ");
return new User(first, last, "default123");
}
}
const alice = new User("Alice", "Smith", "secret123");
console.log(alice.fullName); // "Alice Smith" (getter — no parentheses!)
alice.age = 25; // setter with validation
console.log(alice.age); // 25
// alice.age = 200; // ❌ Error: Invalid age!
// console.log(alice.#password); // ❌ SyntaxError: private field
// Static methods
const bob = User.create("Bob Jones");
console.log(bob.fullName); // "Bob Jones"
console.log(User.count); // 2Tip
Tip
Use private fields (#) for any data that should not be accessed or modified from outside the class. Passwords, internal state, and implementation details should be private. This prevents accidental misuse and makes your API cleaner.
Classes are syntactic sugar over prototypes.
Common Mistake
Warning
Creating a getter and setter with the same name as a regular property causes infinite recursion. Use an underscore convention: set age(val) { this._age = val; } get age() { return this._age; }. The getter/setter name must differ from the stored property.
Practice Task
Note
Build a BankAccount class: (1) Private #balance field. (2) Getter for balance. (3) Setter that validates deposits (no negative amounts). (4) Static method to compare two accounts. (5) A withdraw method with insufficient funds check.
Quick Quiz
Key Takeaways
- Getters and setters let you control how properties are accessed and modified — adding validation, formatting, or computed values.
- get — Access computed value like a property: user.fullName (no parentheses)
- set — Validate or transform on assignment: user.age = 150 → throws error
- Private fields (#) — class { #password; } — truly private, can't be accessed outside