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: 1The key to method chaining is returning this from each method that you want to be chainable.
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.
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 4This 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 InheritanceOverriding & Area MethodStatic Shape Counter9Static Methods & Properties
Class-Level vs. Instance-LevelStatic PropertiesStatic Utility MethodsRecap challenge