What are higher order functions in JavaScript?

In JavaScript, a higher-order function is a function that takes one or more functions as arguments, and/or returns a function as its result. These functions are called higher-order because they operate on other functions, rather than just operating on data.

Example higher order function

One of the most common examples of a higher-order function is the Array.prototype.map() method. This method takes a function as an argument and applies it to each element in an array, returning a new array with the results.

For example, let's say you have an array of numbers and you want to square each number:

Copy codelet numbers = [1, 2, 3, 4, 5]; let squaredNumbers = numbers.map(function(number) { return number * number; }); console.log(squaredNumbers); // [1, 4, 9, 16, 25]

In this example, the map() method takes a function as an argument, which squares each number in the array.

Another example of a higher-order function is the Array.prototype.filter() method. This method takes a function as an argument and filters the elements of an array based on the function's return value.

For example, let's say you have an array of numbers and you want to filter out all the even numbers:

Copy codelet numbers = [1, 2, 3, 4, 5]; let oddNumbers = numbers.filter(function(number) { return number % 2 !== 0; }); console.log(oddNumbers); // [1, 3, 5]

In this example, the filter() method takes a function as an argument, which filters out even numbers in the array.

Another example is the setTimeout() function, which takes two arguments: a function, and a delay in milliseconds. It executes the function after the delay.

Copy codesetTimeout(() => console.log("Hello"), 1000); 

Return a function

A higher-order function can also be a function that returns another function as its result. For example, the following function returns a new function that adds a specific value to its argument:

Copy codefunction add(x) { return function(y) { return x + y; } } let addFive = add(5); console.log(addFive(3)); // 8

In this example, the add() function is a higher-order function because it returns a new function, which is used to add a specific value to its argument.

In summary, higher-order functions are a fundamental concept in JavaScript and functional programming. They allow you to abstract away common operations, such as mapping, filtering, and composing, making your code more readable and reusable. They also enable you to write more powerful and expressive code by allowing you to manipulate functions in the same way as other data types.

Continue Reading