Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
First-Class Functions
3.
Example of First Class Functions
4.
Higher-Order Functions in JavaScript
5.
Example of Higher-Order Functions
6.
The .reduce() Method
7.
The .map() Method
8.
The .filter() Method
9.
The .forEach() Method
10.
Benefits of Higher-Order Functions
11.
FAQs
11.1.
When is it OK to employ higher-order functions?
11.2.
Is it possible to decrease a higher-order function?
11.3.
What is the difference between a higher-order function and a callback?
11.4.
Is recursion a higher-order function?
11.5.
Is it true that recursion is a higher-order function?
12.
Conclusion
Last Updated: Mar 27, 2024
Easy

Higher-Order Functions in JS

Author Divyansh Jain
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

You want to learn the concept of Higher-Order of Functions to make your code better and improve your code in a simpler and easy manner. Then you are at the right place. 

Functions can be assigned to variables in Javascript in the same manner that strings, arrays and other objects can. They can be supplied as parameters to other functions or returned from them. That’s what precisely we call them as Higher order functions. 

Also Read About, Javascript hasOwnProperty

First-Class Functions

If functions in a programming language are handled like other variables, it is argued that the language has first-class functions. As a result, the functions can be assigned to other variables, supplied as arguments, or returned by another function.
Functions are treated as first-class citizens in JavaScript. This indicates that functions are just another sort of object and are merely a value.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example of First Class Functions

The basic example of First Class Functions is given below where we directly passing the arguments and returning the result. 

const Calculate = {
    addition:(a,b) => {
return `${a} + ${b} = ${a+b}`;
    },
    subtraction:(a, b) => {
        return `${a} - ${b} = ${a-b}`
    },
    multiplication:(a, b) => {
        return `${a} * ${b} = ${a*b}`
    },
    division:(a, b) => {
        if(b!=0) return `${a} / ${b} = ${a/b}`;
        return `Not divisible by Zero!!!`;
    }
 
}
console.log(Calculate.addition(100, 50));
console.log(Calculate.subtraction(100,30));
console.log(Calculate.multiplication(5,10));
console.log(Calculate.division(100,25));

This is a simple code to perform basic operations on Numbers. The output of the above code is given below. 

Output

100 + 50 = 150
100 - 30 = 70 
5 * 10 = 50 
100 / 25 = 4 

Next, let us look the Higher-Order functions in detail: 

Higher-Order Functions in JavaScript

Functions in JavaScript can take primitive types (such as numbers or characters) and objects (such as arrays, plain objects, regular expressions, and so on) as arguments and return a primitive type or object.

Is it, nevertheless, feasible to utilize functions as values? Assigning functions to variables, using them as arguments, or even returning them? Yes, that is conceivable!

Now using our super Power of Higher-Order Functions, let us look at an example to be more clear on this topic. 
 

Dance Party GIF by Cartoon Network Asia

Source: Giphy

Example of Higher-Order Functions

Now we are going to use the above concept to code the same program we did earlier in First-Class Functions. This will make our code easy and simple.

function Calculate(Operation , initialValue, numbers) {
  let total = initialValue;
  for (const number of numbers) {
    total = Operation(total, number);
  }
  return total;
}
function addition(n1, n2) {
  return n1 + n2;
}
function multiplication(n1, n2) {
  return n1 * n2;
}
console.log(Calculate(addition, 0, [1, 2, 4]));      
console.log(Calculate(multiplication, 1, [1, 2, 4]));

In the above code we have created the functions addition and multiplication and then we have used these functions as arguments in Calculate function. Let us test it and look at the results.

Output

7
8

Our code works fine and gives the desired output hence our concept works well. 

The .reduce() Method

The reduce() method calls a user-supplied "reducer" callback function on each element of the array, sending in the result of the previous element's calculation. When the reducer is applied to all elements of the array, the outcome is a single value. 

There is no "return value of the previous calculation" the first time the callback is executed. An starting value can be used in its stead if one is provided. Otherwise, the original value for the array element at index 0 is used, and iteration begins with the next element (index 1 instead of index 0).

Syntax:

.reduce((arguments) =>{
/*...............*/
})

Example:

const arr = [10,20,30,40,50];
const ans = arr.reduce((accumulator, currentIndexValue) => {
               return accumulator + currentIndexValue;
});
console.log(ans);

Output:

150

The .map() Method

The.map() method applies a callback function to each element of an array. It returns a new array containing the callback function's return values.
The original array is not changed, and the returned array may have elements that are different from those in the original array.

Syntax:

.map((arguments) =>{
/*...............*/
})

Example:

const names = [‘Ram’,’ Shyam’,’ Ghanshyam’];
const updatednames = names.map(members => {
         return ‘Mr.’+names ; 
})
console.log(updatednames);

Output:

Mr.Ram, Mr.Shyam, Mr.Ghanshyam

In the above example we have not changed the names but we have appended ‘Mr.’ in front of the names. 

The .filter() Method

The .filter() method executed a callback function for all the elements of the array upon which it is called which satisfies the condition stated in the method.

Syntax:

.filter((arguments) =>{
/*...............*/
})

Example:

const arr = [3,5,4,1,6,8];
const result = arr.filter( x => {
        return x%2==0;
});
console.log(result);

Output:

4,6,8

In the above function all the elements which are divisible by 2 have been filtered into the result.

The .forEach() Method

The .forEach() method performs a callback function on each entry in the array in the order specified.

Syntax:

.forEach((arguments) =>{
/*...............*/
})

Example:

const arr = [12,14,16.18,20];
arr.forEach(x => {
          console.log(x);
});

Output:

12,14,16,18,20

 

 

In the above example, console.log() method have been executed for each and every value present in the array arr. 

You can also try on an online javascript compiler.

Benefits of Higher-Order Functions

  • By providing alternative operation functions, we may reuse the calculate() function to handle multiple operations: addition, multiplication, and more.
  • The higher-order functions favor the single-responsibility principle and help reduce code duplication. 
  • The program is much easier to comprehend, and the programmer's aim is clearly communicated in the code.

FAQs

When is it OK to employ higher-order functions?

Higher-order functions are frequently used to abstract how to work with various data types. Filter(), for example, does not have to work with string arrays. Because you can pass in a function that knows how to deal with a different data type, it might just as readily filter numbers.

Is it possible to decrease a higher-order function?

Reduce is a built-in Higher-Order Function in JavaScript that is quite handy. Reduce is ideal for calculating an array's total. Reduce will take a collection of numbers in an array and return a single value, the sum of those integers.

What is the difference between a higher-order function and a callback?

A higher-order function is one that accepts another function as an input and/or returns another function to its callers. A callback function is one that is supplied to another function with the expectation that it will be called by the other function. A higher-order function is one that accepts another function as an input and/or returns another function to its callers. A callback function is one that is supplied to another function with the expectation that it will be called by the other function.

Is recursion a higher-order function?

It's not a "higher-order function" that you're referring to in your update. Instead of returning a function, it returns the result of a recursive call to itself.

Is it true that recursion is a higher-order function?

So, why does the order of JavaScript functions matter? When a program has several scopes and a number of functions, the order in which they are called matters a lot. Functions in the inner scope must be able to access functions in the outer scope for a JavaScript program to work properly.

Conclusion

To summarize the above blog we have learned about Higher-Order Functions in Javascript. Also, we have compared it to a normal First-Order Function. We have also mentioned the benefits we get upon using Higher-Order Functions.

Hope you learned something. But the knowledge never stops, So to learn more you can visit our website for more articles. Check out our articles on Debounce and ThrottleImplement Linear Search and Binary Search in an Array, and Explain Memoization in Javascript

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available, Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Happy Learning Ninja :) 

Previous article
Anonymous Functions in JavaScript
Next article
First-Class Functions
Live masterclass