Thanks to visit codestin.com
Credit goes to www.rameshfadatare.com

JavaScript Higher-Order Functions

In this chapter, we will learn about JavaScript higher-order functions. Higher-order functions are functions that can take other functions as arguments, return functions, or both. They are a powerful feature in functional programming. We will cover:

  • What are Higher-Order Functions?
  • Using Functions as Arguments
  • Returning Functions from Functions
  • Common Higher-Order Functions: map, filter, and reduce
  • Simple Programs using Higher-Order Functions

What are Higher-Order Functions?

A higher-order function is a function that operates on other functions, either by taking them as arguments or by returning them. Higher-order functions allow you to write more modular and reusable code.

Using Functions as Arguments

You can pass a function as an argument to another function. This allows you to create functions that can perform a variety of tasks based on the functions passed to them.

Example

function applyOperation(a, b, operation) {
  return operation(a, b);
}

let sum = applyOperation(5, 10, function(x, y) {
  return x + y;
});

console.log("Sum:", sum); // Output: Sum: 15

In the example above, the applyOperation function takes two numbers and a function (operation) as arguments. It applies the operation to the numbers and returns the result.

Returning Functions from Functions

You can return a function from another function. This allows you to create functions that generate other functions.

Example

function createMultiplier(multiplier) {
  return function(number) {
    return number * multiplier;
  };
}

let double = createMultiplier(2);
console.log("Double of 5:", double(5)); // Output: Double of 5: 10

let triple = createMultiplier(3);
console.log("Triple of 5:", triple(5)); // Output: Triple of 5: 15

In the example above, the createMultiplier function returns a new function that multiplies its argument by the specified multiplier.

Common Higher-Order Functions: map, filter, and reduce

map

The map function creates a new array by applying a function to each element of an existing array.

Example

let numbers = [1, 2, 3, 4, 5];
let squares = numbers.map(function(number) {
  return number * number;
});

console.log("Squares:", squares); // Output: Squares: [1, 4, 9, 16, 25]

filter

The filter function creates a new array with all elements that pass a test implemented by the provided function.

Example

let numbers = [1, 2, 3, 4, 5, 6];
let evenNumbers = numbers.filter(function(number) {
  return number % 2 === 0;
});

console.log("Even numbers:", evenNumbers); // Output: Even numbers: [2, 4, 6]

reduce

The reduce function applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

Example

let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);

console.log("Sum:", sum); // Output: Sum: 15

Simple Programs using Higher-Order Functions

Program 1: Convert an Array of Strings to Uppercase

let strings = ["hello", "world", "javascript"];
let uppercasedStrings = strings.map(function(str) {
  return str.toUpperCase();
});

console.log("Uppercased strings:", uppercasedStrings); // Output: Uppercased strings: ["HELLO", "WORLD", "JAVASCRIPT"]

Program 2: Filter Positive Numbers from an Array

let numbers = [-1, 2, -3, 4, -5];
let positiveNumbers = numbers.filter(function(number) {
  return number > 0;
});

console.log("Positive numbers:", positiveNumbers); // Output: Positive numbers: [2, 4]

Program 3: Calculate the Product of an Array of Numbers

let numbers = [1, 2, 3, 4, 5];
let product = numbers.reduce(function(accumulator, currentValue) {
  return accumulator * currentValue;
}, 1);

console.log("Product:", product); // Output: Product: 120

Program 4: Chain map and filter to Process an Array

let numbers = [1, 2, 3, 4, 5, 6];
let result = numbers
  .filter(function(number) {
    return number % 2 === 0;
  })
  .map(function(number) {
    return number * number;
  });

console.log("Result:", result); // Output: Result: [4, 16, 36]

Program 5: Use reduce to Count the Occurrences of Elements in an Array

let fruits = ["apple", "banana", "apple", "orange", "banana", "apple"];
let fruitCount = fruits.reduce(function(accumulator, fruit) {
  if (!accumulator[fruit]) {
    accumulator[fruit] = 1;
  } else {
    accumulator[fruit]++;
  }
  return accumulator;
}, {});

console.log("Fruit count:", fruitCount); // Output: Fruit count: { apple: 3, banana: 2, orange: 1 }

Conclusion

In this chapter, you learned about JavaScript higher-order functions, including their definition, using functions as arguments, returning functions from functions, and common higher-order functions like map, filter, and reduce. We also provided various use cases with simple programs to demonstrate the usage of higher-order functions. Higher-order functions are a powerful feature in JavaScript, allowing you to write more modular, reusable, and functional code.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top