DEV Community

DIWAKARKASHYAP
DIWAKARKASHYAP

Posted on

Higher Order Function (HOF) in JavaScript

A high order function is a function which takes other function as an argument and Returns function, the other and simple definition is, A high-order function in programming is a function that does at least one of the following:

1-Takes one or more functions as arguments (i.e., procedural parameters),
2-Returns a function as its result.

High-order functions are a key part of functional programming, and they're also used quite widely in more imperative-style programming. High-order functions allow us to create more generic functions, reduce code duplication, and can lead to code that is easier to read and maintain.

Here's an example of a high-order function in JavaScript:


function map(arr, func) {
    let result = [];
    for(let i = 0; i < arr.length; i++){
        result.push(func(arr[i]));
    }
    return result;
}

let array = [1, 2, 3, 4, 5];
let square = function(x) {
    return x * x;
}

console.log(map(array, square)); // Outputs: [1, 4, 9, 16, 25]
Enter fullscreen mode Exit fullscreen mode

In this case, map is a high-order function because it takes a function (func) as an argument. This high-order function applies the function func to every element in the array arr and returns a new array with the results.

Thank you for reading, please follow me on Twitter, i regularly share content about Javascript, and React and contribute to Opensource Projects

Twitter-https://twitter.com/Diwakar_766

Github-https://github.com/DIWAKARKASHYAP

Top comments (0)