Higher-Order Functions in JavaScript

Nozibul Islam - Sep 15 - - Dev Community

What is Higher-Order Functions?

Higher-Order Functions are functions that can accept other functions as arguments or return functions as values. They provide us with a powerful way to write reusable code that can be applied in various scenarios. JavaScript has several commonly used higher-order functions, including map(), filter(), and reduce(). JavaScript is often referred to as a functional programming language due to the presence of higher-order functions.

Conditions of a Higher-Order Function:

  1. It can accept one or more functions as parameters.
  2. It can return a function as a value.

Example:

function add(x) {
  return function(y) {
    return x + y;
  };
}
Enter fullscreen mode Exit fullscreen mode

In JavaScript, there are several popular higher-order functions that fulfill these conditions.

map(): The map() function applies a function to each element of an array and creates a new array. It does not modify the original elements but rather creates a new value by applying the function.

Example:

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(function(num) {
  return num * 2;
});
console.log(doubled); // Logs [2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode

In this example, we use map() to create a new array called doubled, which multiplies each element of the numbers array by 2.

filter(): The filter() function applies a filtering function to the elements of an array and returns only the elements that satisfy a specific condition. It creates a new array containing the filtered elements.

Example:

const numbers = [1, 2, 3, 4];
const even = numbers.filter(function(num) {
  return num % 2 === 0;
});
console.log(even); // Logs [2, 4]
Enter fullscreen mode Exit fullscreen mode

In this example, we use filter() to create a new array called, which contains only the even numbers from the numbers array.

reduce(): The reduce() function accumulates the elements of an array into a single value. It applies a combining function to each element and the previous accumulated value to create a new value.

Example:

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(sum); // Output: 15
Enter fullscreen mode Exit fullscreen mode

In this example, the reduce() function accumulates the numbers of the array by adding each element to the accumulated value. The final result is stored in the sum variable, which equals 15.

These higher-order functions provide powerful ways to manipulate arrays in JavaScript by applying custom functions to each element or filtering and reducing them based on specific conditions.

. . . . .
Terabox Video Player