DEV Community

Cover image for Understanding Method Chaining in JavaScript: A Practical Example with a Calculator
Gowri Shankar S
Gowri Shankar S

Posted on

1

Understanding Method Chaining in JavaScript: A Practical Example with a Calculator

Method chaining in JavaScript is when you call multiple methods on the same object in a single line of code. Each method returns the object itself, so you can "chain" the next method right after it. It makes your code cleaner and more readable.

Example :

// Invoking the below chainable calc function should output the result 20
calculator().add(7).subtract(5).multiply(20).divide(2).getResult();
Enter fullscreen mode Exit fullscreen mode

Instead of writing multiple lines to perform operations, method chaining lets you stack them up in one smooth sequence.

Building a Chainable Calculator in JavaScript

Let’s see method chaining in action by building a simple chainable calculator in JavaScript. This calculator will allow us to chain mathematical operations like addition, subtraction, multiplication, and division together in a clean and readable way.

Approach 1: Using a Class

We'll create a Calculator class with basic arithmetic operations that return the instance (this), enabling chaining.

class Calculator {
  constructor() {
    this.result = 0;
  }

  add(value) {
    this.result += value;
    return this;
  }

  subtract(value) {
    this.result -= value;
    return this;
  }

  multiply(value) {
    this.result *= value;
    return this;
  }

  divide(value) {
    if (value === 0) {
      return this;
    }
    this.result /= value;
    return this;
  }

  getResult() {
    return this.result;
  }
}
Enter fullscreen mode Exit fullscreen mode

Testing the Calculator

const calc = new Calculator();
const result = calc.add(5).subtract(2).multiply(3).divide(4).getResult();
console.log(result); // Output: 2.25

Enter fullscreen mode Exit fullscreen mode

Approach 2: Using Functions

In this approach, we create functions for each operation that update an object and return it, so you can chain the operations together. The object's state is kept inside the function.

function calculator() {
  let result = 0;  // Start with 0

  return {
    add(value) {
      result += value;
      return this;
    },
    subtract(value) {
      result -= value;
      return this;
    },
    multiply(value) {
      result *= value;
      return this;
    },
    divide(value) {
      if (value === 0) {
        return this;
      }
      result /= value;
      return this;
    },
    getResult() {
      return result;
    }
  };
}

// Usage
const result = calculator().add(10).subtract(5).multiply(20).divide(2).getResult();
console.log(result);  // Output: 50

Enter fullscreen mode Exit fullscreen mode

Practical Use Cases for Method Chaining

Here are some everyday examples where method chaining can be super helpful.

1. Making API Calls (e.g., with Axios)

Method chaining makes working with API requests straightforward. Instead of handling the response, error, and final steps separately, you can chain them together like one continuous operation.

axios.get('/user')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  })
  .finally(() => {
    console.log('Request completed');
  });

Enter fullscreen mode Exit fullscreen mode

Each part of the process is chained, so you don’t need to clutter your code with multiple callbacks.

2. Querying a MongoDB Database

With MongoDB, you can chain queries together to filter, sort, and limit your results. This approach lets you build your queries gradually, step by step, making the process smooth and easy to follow.

  const result = await users.find()
    .filter({ age: { $gt: 18 } })  // Filter users where age > 18
    .sort({ name: 1 })  // Sort by name in ascending order
    .limit(10)  // Limit results to 10
    .toArray();  // Convert the result to an array
Enter fullscreen mode Exit fullscreen mode

You add one thing at a time, but it all happens in one smooth flow.

3. DOM Manipulation (Like jQuery)

When you're working with the DOM, you can chain multiple actions together to manipulate an element in one go. It’s like telling the browser, "Do this, then that."

$('#element')
  .css('color', 'red')
  .fadeIn(500)
  .slideUp(300)
  .text('Hello, World!');

Enter fullscreen mode Exit fullscreen mode

Instead of writing separate lines for each action, you just chain them together, making your code more concise and readable.

Conclusion

In this post, we’ve explored the concept of method chaining in JavaScript and built a chainable calculator to demonstrate it. By using method chaining, we’ve been able to perform multiple mathematical operations in a clean and readable manner, making the code more intuitive.

Method chaining is a powerful feature commonly used in JavaScript libraries and frameworks. It not only reduces the complexity of the code but also enhances the readability, making it easier to understand and maintain.

If you found this post helpful, feel free to like 👍, share 🔄, and connect with me on LinkedIn 👥!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

👋 Kindness is contagious

Please show some love ❤️ or share a kind word in the comments if you found this useful!

Got it!