Menu
Coddy logo textTech

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 Smith

Notice that we don't call these methods with parentheses. They behave just like properties but execute code when accessed or modified.

challenge icon

Challenge

You're given a User class with an age property. Your task is to add a getter and setter for age that:

  1. Getter <strong>get age()</strong>: returns the stored age
  2. 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!"

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 Smith

Try 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)

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming