CodeGym /Java Course /Frontend SELF EN /Higher-Order Functions

Higher-Order Functions

Frontend SELF EN
Level 37 , Lesson 4
Available

5.1 Key Concepts

Higher-order functions are a big part of functional programming and are widely used in JavaScript. They let us write more abstract, compact, and reusable code.

What are higher-order functions?

Higher-order functions are functions that take other functions as arguments or return functions as results. They let you use functions as first-class objects, which helps create more abstract and modular programs.

Examples of higher-order functions

  1. Passing functions as arguments.
  2. Returning functions from other functions.

5.2 Passing Functions as Arguments

Using built-in array methods

JavaScript provides tons of built-in methods for working with arrays that are higher-order functions, like forEach(), map(), filter(), reduce(), and others.

1. Method forEach()

The forEach() method executes a given function once for each element in the array.

JavaScript
    
      const numbers = [1, 2, 3, 4, 5];

      numbers.forEach(function(number) {
        console.log(number);
      });
      // Output: 1 2 3 4 5
    
  

2. Method map()

The map() method creates a new array with the results of calling a specified function for each element in the array.

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

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

3. Method filter()

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

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

      console.log(evenNumbers);
      // Output: [2, 4]
    
  

4. Method reduce()

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

JavaScript
    
      const numbers = [1, 2, 3, 4, 5];
      const sum = numbers.reduce(function(total, number) {
        return total + number;
      }, 0);

      console.log(sum);
      // Output: 15
    
  

5.3 Returning Functions from Other Functions

Higher-order functions can return other functions, which allows for creating more flexible and customizable functions.

1. Currying

Currying is the process of transforming a function that takes multiple arguments into a function that takes one argument and returns another function that takes the next argument, and so on.

Example of currying:

JavaScript
    
      function multiply(a) {
        return function(b) {
          return a * b;
        };
      }

      const multiplyByTwo = multiply(2);
      console.log(multiplyByTwo(5)); // Output: 10

      const multiplyByThree = multiply(3);
      console.log(multiplyByThree(5)); // Output: 15
    
  

2. Creating Customizable Functions

Higher-order functions allow creating functions that can be customized with arguments.

Example:

JavaScript
    
      function createGreeting(greeting) {
        return function(name) {
          console.log(`${greeting}, ${name}!`);
        };
      }

      const sayHello = createGreeting('Hello');
      sayHello('Alice'); // Output: Hello, Alice!

      const sayHi = createGreeting('Hi');
      sayHi('Bob'); // Output: Hi, Bob!
    
  

5.4 Practical Use

Let's look at practical uses of higher-order functions.

Function compose()

The compose() function lets you combine several functions into one that applies them in sequence:

JavaScript
    
      function compose(...functions) {
        return function(initialValue) {
          return functions.reduceRight((value, func) => func(value), initialValue);
        };
      }

      const addOne = x => x + 1;
      const double = x => x * 2;
      const addOneAndDouble = compose(double, addOne);
      console.log(addOneAndDouble(5)); // Output: 12 (first adds 1 to 5, then doubles the result)
    
  

Asynchronous Higher-Order Functions

Asynchronous higher-order functions let you handle async operations like API requests or working with timers:

JavaScript
    
      function fetchData(callback) {
        setTimeout(() => {
          callback('Data received');
        }, 1000);
      }

      function processData(data) {
        console.log(data);
      }

      fetchData(processData);
      // Output: Data received (after 1 second)
    
  
1
Task
Frontend SELF EN, level 37, lesson 4
Locked
Currying Multiplication
Currying Multiplication
1
Task
Frontend SELF EN, level 37, lesson 4
Locked
Greeting Function
Greeting Function
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION