Menu
Coddy logo textTech

Method chaining pattern

Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 16 of 56.

Method chaining is a programming pattern that allows you to call multiple methods on the same object in a single statement. Each method returns the object itself (this), enabling you to call the next method on the same line.

Create a simple counter object:

const counter = {
  count: 0,
  
  increment() {
    this.count++;
    return this;
  },
  
  decrement() {
    this.count--;
    return this;
  },
  
  getValue() {
    return this.count;
  }
};

Now you can chain methods together:

// Chain multiple operations
counter.increment().increment().decrement();

// The count is now 1
console.log(counter.getValue()); // Output: 1

The key to method chaining is returning this from each method that you want to be chainable.

challenge icon

Challenge

You're given a calculator object that already has add() and subtract() methods. Your task is to add multiply and divide methods that return this to enable chaining.

Cheat sheet

Method chaining allows you to call multiple methods on the same object in a single statement. Each method returns the object itself (this), enabling the next method to be called on the same line.

To enable method chaining, return this from each method:

const counter = {
  count: 0,
  
  increment() {
    this.count++;
    return this;
  },
  
  decrement() {
    this.count--;
    return this;
  },
  
  getValue() {
    return this.count;
  }
};

Chain multiple methods together:

counter.increment().increment().decrement();
console.log(counter.getValue()); // Output: 1

Try it yourself

import { calculator } from './calculator.js';

// Test code - don't modify
const result1 = calculator.add(10).multiply(2).getValue();
console.log(result1); // Should output 20

// Reset for second test
calculator.value = 0;
const result2 = calculator.add(20).divide(4).subtract(1).getValue();
console.log(result2); // Should output 4
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