🚀 Mastering JavaScript Method Chaining Through Closures!
While working on the LeetCode 30-day challenge, I encountered an interesting problem: building a calculator that supports method chaining! This is not only a great coding exercise but also a perfect way to understand closures in JavaScript.
👉 Why Closures? When you implement this problem functionally, it demonstrates how closures allow access to variables even after the outer function has completed execution. It’s a neat pattern for maintaining state across multiple method calls. While this can be done using classes, the functional approach really shines here!
🔍 Problem: Implement a Calculator with Method Chaining
We need to build a calculator that allows chaining operations like add(), subtract(), multiply(), divide(), and power() in sequence, all while returning the final result.
💻 Solution 1: Class-Based Approach
class Calculator {
constructor(value) {
this.value = value;
}
add(value) {
this.value += value;
return this;
}
subtract(value) {
this.value -= value;
return this;
}
multiply(value) {
this.value *= value;
return this;
}
divide(value) {
if (value === 0) throw new Error("Division by zero is not allowed");
this.value /= value;
return this;
}
power(value) {
this.value = Math.pow(this.value, value);
return this;
}
getResult() {
return this.value;
}
}
const result = new Calculator(10).add(5).multiply(2).getResult();
console.log(result); // 30
💻 Solution 2: Functional Approach (Closures)
function Calculator(value) {
let result = value;
return {
add: function(value) {
result += value;
return this;
},
subtract: function(value) {
result -= value;
return this;
},
multiply: function(value) {
result *= value;
return this;
},
divide: function(value) {
if (value === 0) throw new Error("Division by zero is not allowed");
result /= value;
return this;
},
power: function(value) {
result = Math.pow(result, value);
return this;
},
getResult: function() {
return result;
}
};
}
const result = Calculator(10).add(5).multiply(2).getResult();
console.log(result); // 30
Where to use this? This approach is ideal for situations like building query builders, configuration setters, or any API where you want to maintain an internal state while providing a clean, chainable interface.
Method chaining is an elegant design pattern, and by combining it with closures, you unlock a powerful way to manage state in JavaScript!
🔎 The Power of Closures
In the functional approach, each method (add, subtract, etc.) has access to the result variable because of closures. Even after the outer Calculator function has returned, the inner functions remember and manipulate result, allowing you to keep chaining calls without losing the current state.
Let me know if you’ve tried something similar or have questions about how this works!
#JavaScript #MethodChaining #LeetCode #Closures #CodingChallenge #Programming
Keep going! 🙌
Nice article, Consider writing frontend interview focused articles at FrontendGeek.com