JavaScript Chain Functions Examples


Written by - Olorunfemi Akinlua
Reviewed by - Deepak Prasad

In JavaScript, we have the ability to chain functions together, which can make code more readable and maintainable. Chaining functions is a technique that allows developers to chain multiple functions together in a sequence, where the output of one function becomes the input of the next function.

In real-life development scenarios, chaining functions can be used to create a sequence of operations on a single piece of data. For example, a developer might want to filter a list of items, map the filtered items to a new format, and then reduce the mapped items to a single value.

In this article, we will discuss how to chain functions in JavaScript from user-defined functions to built-in higher-order functions.

 

Chaining user-defined functions

When we work in JavaScript, we create different user-defined functions that we might want to link together. Instead of storing the result of one function to a variable, we can chain the function to another function to pass the value returned by the function.

Here's an example of chaining multiple functions together

function add(x) {
    return x + 2;
}

function multiply(x) {
    return x * x;
}

function subtract(x) {
    return x - 3;
}

function stat(x, y) {
    return (x + y / Math.PI) * Math.E;
}

let result = stat(subtract(multiply(add(5))), 4);
console.log(result);

Output

128.50198802684514

In this example, the add function takes a single argument and returns the result of adding 2 to it. The multiply function takes a single argument and returns the exponentiation of the argument. The subtract function takes a single argument and returns the result of subtracting 3 from it. Then, the stat function takes two arguments and returns the addition of the arguments divided by pi and multiply by e.

Each function is called one after the other, starting with the innermost function call and working outwards. In this case, the add(5) is called first, it returns 7 and the result is passed to the multiply function, 7*7 =49, then the result of the multiply function is passed to the subtract function, 49-3 = 46. Finally, the result of the subtract function is passed to the stat function, (46 + 4 / 3.149 ) * 2.718 = 128.50198802684514.

 

Method chaining

You can also chain functions together using method chaining, which is a pattern where an object's methods return the object itself, allowing you to call multiple methods on the same object in one statement. Here we store the functions within an object and therefore we can use the dot notation to call on each function.

Here is an illustration of how we can method chain by chaining different functions.

let obj = {
    value: 1,
    add: function (x) {
        this.value += x;
        return this;
    },
    multiply: function () {
        this.value *= this.value;
        return this;
    },
    subtract: function (x) {
        this.value -= x;
        return this;
    },
};

let result = obj.add(5).multiply().subtract(3).value;
console.log(result);

Output

33

In this example, the add, multiply and subtract methods return the obj object, allowing you to chain multiple methods calls together.

 

Chaining Higher-Order functions

One of the most commonly used chains of functions in JavaScript is the map(), filter() and reduce() functions. These are functional programming methods that can be combined to perform a variety of operations on an array.

An example of chaining map(), filter() and reduce() function:

const numbers = [11, 23, 83, 49, 50];
const sum = numbers
    .filter((n) => n % 2 === 0)
    .map((n) => n * 2)
    .reduce((sum, n) => sum + n, 0);
console.log(sum);

Output

100

In this example, we have an array of numbers and we want to get the sum of all even numbers that are multiplied by 2. The filter() function is used to filter out all odd numbers, the map() function is used to double the remaining numbers and the reduce() function is used to add up all the numbers.

 

Summary

Chaining functions is a powerful technique that allows developers to perform a series of operations on a single piece of data in a readable and maintainable way. Chaining functions can be used to filter, map, reduce and work with user-defined functions. With the use of functional programming methods such as map(), filter(), reduce(), developers can chain multiple functions together to perform a variety of operations.

 

References

Functions - JavaScript | MDN (mozilla.org)
Chain functions in JavaScript - node.js - Stack Overflow

 

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on LinkedIn.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment