Menu
Coddy logo textTech

Methods that modify state

Part of the Object Oriented Programming section of Coddy's JavaScript journey. Lesson 15 of 56.

Methods in JavaScript classes can modify the state (properties) of an object. This is one of the key features of object-oriented programming.

Let's create a simple BankAccount class:

class BankAccount {
  constructor(owner, balance = 0) {
    this.owner = owner;
    this.balance = balance;
  }
  
  deposit(amount) {
    this.balance += amount;
  }
}

Now let's create an instance and modify its state:

const johnsAccount = new BankAccount("John", 100);
console.log(johnsAccount.balance); // Outputs: 100

johnsAccount.deposit(50);
console.log(johnsAccount.balance); // Outputs: 150

In this example, the deposit() method modifies the internal state (the balance property) of the BankAccount instance.

We can add more state-modifying methods:

class BankAccount {
  constructor(owner, balance = 0) {
    this.owner = owner;
    this.balance = balance;
  }
  
  deposit(amount) {
    this.balance += amount;
  }
  
  withdraw(amount) {
    if (amount <= this.balance) {
      this.balance -= amount;
    }
  }
  
  transfer(amount, toAccount) {
    if (amount <= this.balance) {
      this.balance -= amount;
      toAccount.balance += amount;
    }
  }
}

Now we can manipulate our bank account in multiple ways.

challenge icon

Challenge

You're given a Thermostat class. Your task is to add methods that modify its temperature state:

  1. increaseTemp() - increases temperature by 1 degree
  2. decreaseTemp() - decreases temperature by 1 degree

Try it yourself

import { Thermostat } from './thermostat.js';

// Test code - don't modify
const livingRoom = new Thermostat("Living Room", 20);

livingRoom.increaseTemp();
livingRoom.increaseTemp();
console.log(livingRoom.currentTemp); // Should output 22

livingRoom.decreaseTemp();
console.log(livingRoom.currentTemp); // Should output 21
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

Practice on your own: Online JavaScript compiler