Higher Order Functions in Javascript

Now a days Javascript became one of the most popular programming language.JavaScript is a versatile and widely-used programming language that plays a crucial role in web development. Developed by Netscape, it is now supported by all major web browsers, making it an essential technology for creating dynamic and interactive web pages.

Let's understand about the higher order functions...

Higher Order Functions:

  • These are the functions in javascript which take functions as input and can give the functions as output.

  • In JavaScript, functions are first-class citizens, meaning they can be treated like any other value, such as a variable or an object.

  • These are also called as first class citizens in javascript.

Callback Functions:

  • These are the functions which can be passed as arguments inside another functions.

  • These functions are called as callback because they can be called at later point of time.

  • Let's look at a simple example of callback function.

  •   function isEven(number) {
          return number % 2 === 0;
      }
    
      const numbers = [1, 2, 3, 4, 5, 6];
    
      // Using filter with the isEven callback
      const evenNumbers = numbers.filter(isEven);
    
      console.log("Even numbers:", evenNumbers);
    
  • The isEven function checks if a given number is even. The numbers array contains some integers. The Array.filter method is used with the isEven callback to create a new array, evenNumbers, containing only the even numbers from the original array.

💡
Some of the resources for learning the higher order functions are:

Higher Order Functions Video

MDN web docs

In JavaScript, higher-order functions can be categorized into several types based on their functionality. Here are some main types of higher-order functions:

  1. Map

    • The map function in JavaScript is a higher-order function that is used to create a new array by applying a provided function to each element of an existing array.

    • It iterates through each item in the array, applies the provided function to each element, and collects the results in a new array.

    • The resulting array has the same length as the original array, but each element is transformed based on the applied function.

    • Purpose: Creates a new array by applying a provided function to each element of the original array.

    • Syntax: array.map(callback(element, index, array), thisArg)

    • Parameters:

      • callback: Function to execute on each element.

      • thisArg (optional): Object to use as this when executing the callback.

    • Example-1:

    •         const numbers = [1, 2, 3, 4];
      
              const squared = numbers.map(function (number,index,array) {
                return number * number;
              });
      
              // squared is now [1, 4, 9, 16]
      

      In this example, the map function is applied to the numbers array. The provided callback function takes each element (number) of the array and squares it. The result is a new array (squared) containing the squared values.

    • Example-2:

    •         const persons = [
                { name: 'Alice', age: 25 },
                { name: 'Bob', age: 30 },
                { name: 'Charlie', age: 22 }
              ];
      
              const names = persons.map(function (person,index,array) {
                return person.name;
              });
      
              // names is now ['Alice', 'Bob', 'Charlie']
      
    • The map function is applied to the persons array.The callback function extracts the name property from each object in the array.The result is a new array (names) containing the extracted names.

  2. Filter

    • The filter function in JavaScript is another higher-order function that operates on arrays.

    • It is used to create a new array containing elements that satisfy a specific condition.

    • The filter function applies a provided function (callback) to each element in the array, and only the elements for which the callback returns true are included in the new array.

    • Purpose: Creates a new array with elements that pass a provided test (callback function).

    • Syntax: array.filter(callback(element, index, array), thisArg)

    • Parameters:

      • callback: Function to test each element of the array.

      • thisArg (optional): Object to use as this when executing the callback.

    • Example-1:

    •         const numbers = [1, 2, 3, 4, 5, 6];
      
              const evenNumbers = numbers.filter(function (number,index,array) {
                return number % 2 === 0;
              });
      
              // evenNumbers is now [2, 4, 6]
      
    • The filter function is applied to the numbers array.The callback function tests whether each number is even (number % 2 === 0).Only the even numbers are included in the new array (evenNumbers).

    • Example-2:

    •         const persons = [
                { name: 'Alice', age: 25 },
                { name: 'Bob', age: 17 },
                { name: 'Charlie', age: 30 }
              ];
      
              const legalAgePersons = persons.filter(function (person) {
                return person.age >= 18;
              });
      
              // legalAgePersons is now [{ name: 'Alice', age: 25 }, { name: 'Charlie', age: 30 }]
      
    • The filter function is applied to the persons array.The callback function tests whether each person is of legal age (person.age >= 18).Only the persons of legal age are included in the new array (legalAgePersons).

  3. Reduce

    • The reduce function in JavaScript is a higher-order function that iterates over the elements of an array and reduces them to a single value.

    • It takes a callback function as its primary argument and applies this function to each element of the array, accumulating the results along the way.

    • Here is the syntax for the reduce function:

    •         const result = array.reduce(function callback(accumulator, currentValue, index, array) {
                // Return the new accumulator value
              }, initialValue);
      
    • Certainly! The reduce function in JavaScript is a higher-order function that iterates over the elements of an array and reduces them to a single value. It takes a callback function as its primary argument and applies this function to each element of the array, accumulating the results along the way.

      Here is the syntax for the reduce function:

      • callback: A function that is called once for each element in the array. It takes four arguments:

        • accumulator: The accumulated result of the previous iterations. If an initialValue is provided, it starts with this value; otherwise, it starts with the first element of the array.

        • currentValue: The current element being processed in the array.

        • index: The index of the current element being processed.

        • array: The array reduce was called upon.

        • initialValue (optional): An initial value for the accumulator. If provided, the reduce function starts with this value; otherwise, it starts with the first element of the array.

      • The reduce function is often used for tasks such as summing up values, calculating averages, finding the maximum or minimum element, or even flattening arrays.

    • Example-1:

    •         const numbers = [1, 2, 3, 4, 5];
      
              const sum = numbers.reduce(function (accumulator, currentValue) {
                return accumulator + currentValue;
              }, 0);
      
              // sum is now 15
      
    • The reduce function is applied to the numbers array.The callback function takes two parameters: accumulator (initially set to 0) and currentValue (each element of the array).The callback function adds each element to the accumulator.The result is the sum of all elements in the array (sum).

    • Example-2:

    •         const numbers = [10, 20, 30, 40, 50];
      
              const average = numbers.reduce(function (accumulator, currentValue, index, array) {
                accumulator += currentValue;
                if (index === array.length - 1) {
                  return accumulator / array.length;
                }
                return accumulator;
              }, 0);
      
              // average is now 30
      
    • The reduce function is applied to the numbers array.The callback function accumulates the sum of all elements (accumulator += currentValue).The average is calculated by dividing the sum by the length of the array when processing the last element.The initial value of the accumulator is set to 0.The result is the average of all elements in the array (average).

  4. forEach

    • The forEach function in JavaScript is a method for iterating over the elements of an array.

    • It provides a way to execute a provided function once for each element in the array, without the need for creating a new array or changing the original one.

    • The forEach function does not return a new array; it simply iterates over the elements and executes the provided function for each of them.

    • Here's the syntax for the forEach function:

    •         array.forEach(function callback(currentValue, index, array) {
                // Code to be executed for each element
              });
      
    • callback: The function to execute for each element in the array.

      • currentValue: The current element being processed in the array.

      • index: The index of the current element being processed.

      • array: The array forEach was called upon.

    • Example-1:

    •         const fruits = ['apple', 'banana', 'orange', 'grape'];
      
              fruits.forEach(function (fruit,index,array) {
                console.log(fruit);
              });
      
              // Output:
              // apple
              // banana
              // orange
              // grape
      
    • The forEach function is applied to the fruits array.The callback function is executed for each element in the array.The console.log statement logs each fruit to the console.

    • Example-2:

    •         const numbers = [1, 2, 3, 4];
      
              numbers.forEach(function (number, index, array) {
                array[index] = number * 2;
              });
      
              // numbers is now [2, 4, 6, 8]
      
    • The forEach function is applied to the numbers array.The callback function doubles each element in the array by updating the array in place.The original array (numbers) is modified.

  5. sort

    • The sort function in JavaScript is a method used to sort the elements of an array.

    • By default, the sort function sorts elements as strings, which may lead to unexpected results for numerical arrays.

    • Therefore, a comparison function can be provided as an argument to customize the sorting behavior.

    • Here's the basic syntax for the sort function:

    •         array.sort([compareFunction]);
      
    • compareFunction (optional): A function that defines the sort order. If omitted, the array is sorted based on the string representation of each element.

    • The sort function modifies the original array in place and returns the sorted array. It does not create a new array.

    • Example-1:

    •         const numbers = [10, 5, 8, 2, 1];
      
              numbers.sort(function (number1, number2) {
                return number1 - number2;
              });
      
              // numbers is now [1, 2, 5, 8, 10]
      
    • The numbers array is sorted using the sort function.The comparison function subtracts number2 from number1. If the result is negative, number1 comes before number2; if it's positive, number2 comes before number1.This ensures a numerical sort order, and the array is now sorted in ascending order.

    • Example-2:

    •         const fruits = ['banana', 'apple', 'orange', 'grape'];
      
              fruits.sort();
      
              // fruits is now ['apple', 'banana', 'grape', 'orange']
      
    • The fruits array is sorted using the sort function without a comparison function.Strings are sorted based on their UTF-16 code unit values, resulting in alphabetical order.The array is now sorted in alphabetical order.

Conclusion

In conclusion, higher-order functions in JavaScript serve as a pivotal feature, enabling a more expressive and modular coding style. These functions, including map, filter, reduce, sort and forEach, play a crucial role in functional programming, emphasizing the use of functions as first-class citizens. By allowing functions to be passed as arguments or returned as results, higher-order functions promote code flexibility, conciseness, and readability.