logologo

Three-D

☕Sign in

    Recent Post:

    Categories:

    nextjsjavascriptthreejshonoreactjs
    featured post image

    snippets

    featured post image

    What is Currying?

    featured post image

    What is an IIFE?

    What are Higher-Order Functions?

    September 22, 2024

    533

    image

    Think you know it all?

    Take quiz!

    In JavaScript, a Higher-Order Function is a function that either: Takes one or more functions as arguments, or Returns a function as its result.

    Higher-order functions allow us to work with functions in a more flexible and reusable way.

    Why are Higher-Order Functions Important?

    Modularity: They help break down tasks into smaller, reusable parts.

    Abstraction: They allow you to write more generalized and abstract code.

    Functional Programming: Higher-order functions are a key concept in functional programming, helping to simplify code that works with data.

    Example of Higher-Order Functions

    code

    function greet(name, callback) {
        console.log("Hello, " + name + "!");
        callback();
    }
    
    function sayGoodbye() {
        console.log("Goodbye!");
    }
    
    greet("Satyendra", sayGoodbye);

    greet is a higher-order function because it takes sayGoodbye (a function) as a parameter. After saying hello, it calls the sayGoodbye function, demonstrating how one function can be used to trigger another.

    Built-in Higher-Order Functions

    JavaScript comes with several built-in higher-order functions, especially for arrays. Some of the most commonly used are: map() filter() reduce()

    map() – Applying a Function to Every Element

    The map() method creates a new array by applying a function to every element of an existing array.

    code

    const numbers = [1, 2, 3, 4];
    
    const squaredNumbers = numbers.map(function(num) {
        return num * num;
    });
    
    console.log(squaredNumbers); // Output: [1, 4, 9, 16]

    map() takes a function that is applied to every element of the numbers array. The result is a new array of squared numbers.

    filter() – Filtering Elements Based on a Condition

    The filter() method creates a new array containing only elements that meet a certain condition.

    code

    const numbers = [1, 2, 3, 4, 5, 6];
    
    const evenNumbers = numbers.filter(function(num) {
        return num % 2 === 0;
    });
    
    console.log(evenNumbers); // Output: [2, 4, 6]

    filter() takes a function that returns true or false. Only the elements that return true are included in the new array.

    reduce() – Reducing an Array to a Single Value

    The reduce() method applies a function to each element of the array, resulting in a single output value.

    code

    const numbers = [1, 2, 3, 4];
    
    const sum = numbers.reduce(function(accumulator, currentValue) {
        return accumulator + currentValue;
    }, 0);
    
    console.log(sum); // Output: 10

    reduce() takes a function that accumulates a result by iterating over each element in the array. The final result is the sum of all numbers.

    Returning Functions from Functions

    Higher-order functions can also return other functions. This allows you to create reusable, customizable behavior.

    code

    function multiplier(factor) {
        return function(num) {
            return num * factor;
        };
    }
    
    const double = multiplier(2);
    const triple = multiplier(3);
    
    console.log(double(5)); // Output: 10
    console.log(triple(5)); // Output: 15

    multiplier is a higher-order function that returns another function. This returned function multiplies any number by the factor passed in.

    Summary

    Higher-order functions can take functions as arguments or return functions as results.

    avaScript provides many built-in higher-order functions like map(), filter(), and reduce()

    Higher-order functions help make your code more modular, abstract, and reusable.