The Wayback Machine - https://web.archive.org/web/20241116123600/https://www.geeksforgeeks.org/higher-order-arrow-functions-in-javascript/
Open In App

Higher-Order Arrow Functions in JavaScript

Last Updated : 23 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite: Arrow Functions 

A Higher-Order function is a function that receives a function as an argument otherwise returns the function as output. The higher-Order Arrow function implies using arrow functions (in ES6) along with Higher-Order functions. 

Needs of Higher Order Arrow Function:

  • In a general way, the programmer instructs on how to perform the function rather than what is needed which increases the length of the code and makes it error-prone.
  • Whereas in the Higher Order Arrow Functions implementation, the code is much short, concise, succinct, easy to debug, and focuses on what is required rather than how to achieve it.
  • We can directly work with the current value instead of accessing it individually using its index (i.e arr[0]).
  • There is no need to create a predefined array and push back the changes.
  • The mutation of objects can be avoided and maintenance of for loop is not required.

Why avoid forEach()? The forEach() function does not return any value so results need to be pushed in a predefined array whereas this is not the case in the map() function. 

javascript




// Data set of students
var Students = [
    { rollNo: 21, name: 'Alpha' },
    { rollNo: 22, name: 'Beta' },
    { rollNo: 23, name: 'Gamma' },
    { rollNo: 24, name: 'Delta' },
    { rollNo: 25, name: 'Omega'}
];
  
// Use forEach() function
var StudentRollNo = [];
  
Students.forEach(function (Student) {
    StudentRollNo.push(Student.rollNo);
});
  
// Display rollNo data
console.log(StudentRollNo);


Output: 

 

The Higher-Order functions are:

JavaScript map() Function: It works on a given array like changing/transforming the whole array and then simply returning it. It does not break the flow for a few conditions. The map() function takes two arguments. The first is a callback which gives the current value of the iteration, the index of the iteration, original array from which the map was called. The other argument is not mandatory which is the value to use as this in the callback. One drawback of using the map() function is that its performance is good only with small data sets. 

javascript




// Data set of students
var Students = [
    { rollNo: 21, name: 'Alpha' },
    { rollNo: 22, name: 'Beta' },
    { rollNo: 23, name: 'Gamma' },
    { rollNo: 24, name: 'Delta' },
    { rollNo: 25, name: 'Omega'}
];
  
// Use map() function
var StudentRollNo = Students.map(function (Student) {
    return Student.rollNo
});
  
// Display rollNo data
console.log(StudentRollNo);


  1. Output: 

 

The implementation of above code using arrow functions. 

javascript




// Data set of students
var Students = [
    { rollNo: 21, name: 'Alpha' },
    { rollNo: 22, name: 'Beta' },
    { rollNo: 23, name: 'Gamma' },
    { rollNo: 24, name: 'Delta' },
    { rollNo: 25, name: 'Omega'}
];
  
// Use map() function with arrow functions
const StudentRollNo =
    Students.map(Student => Student.rollNo);
  
// Display Roll no data
console.log(StudentRollNo);


Output: 

 

Note: For more information refer to: Maps in JavaScript

JavaScript reduce() Function: It is similar to the map() function in terms of a callback for every element of the array. But the difference is that it reduces passes the result of this callback from the original array to another. The result is termed as an accumulator which can be of anything integer, character, string, object, map, etc and should be passed while invoking. The callback now gets the accumulator, current value, index of iteration, and whole array. In simple words, the accumulator accumulates all the return values. Its value is the collection of previously returned accumulations. 

javascript




// Data set of students
var Students = [
    { rollNo: 21, name: 'Alpha', prizesWon: 1 },
    { rollNo: 22, name: 'Beta', prizesWon: 3 },
    { rollNo: 23, name: 'Gamma', prizesWon: 0 },
    { rollNo: 24, name: 'Delta', prizesWon: 0 },
    { rollNo: 25, name: 'Omega', prizesWon: 1}
];
  
// Using reduce() function
var totalPrizes = Students.reduce(function (accumulator, Student) {
    return accumulator + Student.prizesWon;
}, 0);
  
// Display total number of prizes won by all
console.log(totalPrizes);


Output:

5

The implementation of above code using arrow functions. 

javascript




// Data set of students
var Students = [
    { rollNo: 21, name: 'Alpha', prizesWon: 1 },
    { rollNo: 22, name: 'Beta', prizesWon: 3 },
    { rollNo: 23, name: 'Gamma', prizesWon: 0 },
    { rollNo: 24, name: 'Delta', prizesWon: 0 },
    { rollNo: 25, name: 'Omega', prizesWon: 1}
];
  
// Using reduce() function with arrow functions
const totalPrizes = Students.reduce(
    (accumulator, Student) => accumulator + Student.prizesWon, 0);
  
// Display total number of prizes won by all
console.log(totalPrizes);


Output:

5

JavaScript find() Function: It also works on an array and returns the first array element which satisfies the condition given in the function. It is similar to map() function. Its performance is not much efficient in case of large data sets although it works fine with small data sets. 

javascript




// Data set of students
var Students = [
    { rollNo: 21, name: 'Alpha', prizesWon: 4 },
    { rollNo: 22, name: 'Beta', prizesWon: 3 },
    { rollNo: 23, name: 'Gamma', prizesWon: 0 },
    { rollNo: 24, name: 'Delta', prizesWon: 4 },
    { rollNo: 25, name: 'Omega', prizesWon: 1}
];
  
// Using find() function
var achievers = Students.find(function (Student) {
    return Student.prizesWon == 4;
});
  
// Display only first Student who won four prizes
console.log(achievers);


Output: 

 The implementation of above code using arrow functions. 

javascript




// Data set of students
var Students = [
    { rollNo: 21, name: 'Alpha', prizesWon: 4 },
    { rollNo: 22, name: 'Beta', prizesWon: 3 },
    { rollNo: 23, name: 'Gamma', prizesWon: 0 },
    { rollNo: 24, name: 'Delta', prizesWon: 4 },
    { rollNo: 25, name: 'Omega', prizesWon: 1}
];
  
// Using find() function with arrow functions
var achievers = Students.find(
    (Student) => Student.prizesWon == 4);
  
// Display only first Student who won four prizes
console.log(achievers);


Output: 

JavaScript filter() Function: The filter() function works on an array and returns an array for filtered items implying the length of the array is reduced. It also receives the similar arguments as map but the difference lies in the callback as it needs to return either true or false. If the value returned is true then the element remains in the array otherwise the element is filtered out. 

javascript




// Data set of students
var Students = [
    { rollNo: 21, name: 'Alpha', prizesWon: 4 },
    { rollNo: 22, name: 'Beta', prizesWon: 3 },
    { rollNo: 23, name: 'Gamma', prizesWon: 0 },
    { rollNo: 24, name: 'Delta', prizesWon: 4 },
    { rollNo: 25, name: 'Omega', prizesWon: 1}
];
  
// Using filter() function
var achievers = Students.filter(function (Student) {
    return Student.prizesWon == 4;
});
  
// Display Students who won four prizes
console.log(achievers);


Output: 

 

The implementation of above code using arrow functions. 

javascript




// Data set of students
var Students = [
    { rollNo: 21, name: 'Alpha', prizesWon: 4 },
    { rollNo: 22, name: 'Beta', prizesWon: 3 },
    { rollNo: 23, name: 'Gamma', prizesWon: 0 },
    { rollNo: 24, name: 'Delta', prizesWon: 4 },
    { rollNo: 25, name: 'Omega', prizesWon: 1}
];
  
// Using filter() function with arrow functions
var achievers = Students.filter(
    (Student) => Student.prizesWon == 4);
  
// Display Students who won four prizes
console.log(achievers);


Output: 



Similar Reads

Difference between First-Class and Higher-Order Functions in JavaScript
Understanding the difference between first-class and higher-order functions in JavaScript is really important. These are big concepts in programming, especially in the kind of coding used for making websites. This article is all about explaining what they are, how they are used, and why they are so important. 1. First-Class Function A programming l
3 min read
JavaScript Higher Order Functions
JavaScript Higher-Order Functions are functions that can accept other functions as arguments, return functions, or both. They enable abstraction and flexibility in code, allowing you to create reusable and modular functions for complex operations, making them essential in functional programming. Syntax: function higherOrderFunction(callback) { // P
3 min read
Higher Order Functions and Currying
Introduction: Generally while programming, we use first class functions which means that the programming language treats functions as values – that you can assign a function into a variable, pass it around. These functions do not take other functions as parameters and never has any function as their return type.To overcome all these shortcomings of
4 min read
Difference between Regular functions and Arrow functions
Regular functions and arrow functions are two common ways to define functions in JavaScript, each with distinct behaviors. Regular functions offer traditional syntax and this context handling, while arrow functions provide a concise syntax and lexical this binding, making them ideal for callbacks and simpler expressions. Table of Content Regular fu
6 min read
What is Higher Order Function in JavaScript ?
A higher-order function is a function that can accept a function as one of its parameters and it can also return a function as its return value or it can do both return as well as accept a function. A higher-order function can also take as well as return other types of values but it either has to take a function as a parameter or return a function
1 min read
What Do Multiple Arrow Functions Mean in JavaScript?
In JavaScript, arrow functions provide a concise syntax for writing function expressions. When you use multiple arrow functions in sequence, it typically signifies a series of nested functions, often used for currying or higher-order functions. These are the following methods to show the multiple arrow functions in JavaScript having different uses:
2 min read
Arrow functions in JavaScript
ES6 introduced the Arrow functions in JavaScript which offer a more concise and readable way to write function expressions. They use the => (arrow) syntax, which not only reduces boilerplate but also binds this lexically, making them particularly useful in certain scenarios like handling callbacks or working within objects. What is Arrow Functio
4 min read
Common use cases for Higher-Order Components in React
A Higher-Order Component (HOC) is a handy tool in React. It's like a wrapper for components that can add extra features or modify how they work. So, you use HOCs to excite up your components, making them more versatile without messing up their original code. It's like giving your components a little upgrade! Use cases for Higher-Order Components:Co
2 min read
Advantages of using custom hooks over higher-order components (HOCs) or render props?
Custom hooks, higher-order components (HOCs), and render props are all techniques used in React to share and reuse logic across components. Each approach has its own advantages. Custom hooks in React are JavaScript functions that utilize built-in React hooks or other custom hooks to encapsulate reusable logic in functional components. Higher-order
2 min read
How to use Higher-Order Components in React ?
Higher-Order Component is an advanced function, which reuses component logic in a React Component and returns an enhanced new component. It wraps commonly used processes to allow their use by different components, such as state modification or props change. Components are wrapped in HOCs, whose goal is to improve them without changing their origina
5 min read
Why would you use a Higher-Order Component in React ?
A Higher-Order Component (HOC) in React is used to share common functionality between multiple components. It's like a function that takes a component as an argument and returns a new enhanced component with added features. By offering a pattern for reusing component logic, HOCs help in crafting more maintainable and cleaner React applications. Thi
3 min read
Higher-Order Types in TypeScript
Higher-order types are among the advanced aspects of Typescript that give priority to types as first-class citizens, similar to higher-order functions of JavaScript that accept a function as an argument or return a function, higher-order types can accept types or return types. These are the following topics that we are going to discuss: Table of Co
6 min read
React.js Higher-Order Components
Higher-order components or HOC is the advanced method of reusing the component functionality logic. It simply takes the original component and returns the enhanced component. Syntax: const EnhancedComponent = higherOrderComponent(OriginalComponent);Reason to use Higher-Order component: Easy to handleGet rid of copying the same logic in every compon
3 min read
How to avoid binding by using arrow functions in callbacks in ReactJS?
In React class-based components when we use event handler callbacks, it is very important to give special attention to the 'this' keyword. In these cases the context this is undefined when the callback function actually gets invoked that's why we have to bind the context of this. Now if binding all the methods of each class is very annoying. Instea
2 min read
When should one use Arrow functions in ES6 ?
In this article, we will try to understand when should one use Arrow functions in ES6 instead of the traditional function's syntax with the help of some examples. Before analyzing why we should use arrow functions, let us first understand the basic details which are associated with the arrow functions (including the syntax of arrow functions and ma
4 min read
PHP Arrow Functions
Arrow functions, also known as "short closures", is a new feature introduced in PHP 7.4 that provides a more concise syntax for defining anonymous functions. Arrow functions allow you to define a function in a single line of code, making your code more readable and easier to maintain. Syntax: $fn = $fun(x) => some_operations Example 1: In this e
1 min read
How to Declare & use Arrow Functions in TypeScript ?
The arrow function is a concise way of declaring the functions in TypeScript with a lexical binding of this object. The arrow function provides us with a shorter way of declaring functions without using the function keyword just with the help of arrows(=>) and the round brackets(). They can be assigned to a variable created using the let, var, a
1 min read
How to Specify Return Type in TypeScript Arrow Functions ?
To Specify the return type in the TypeScript arrow function, we have multiple approaches. In this article, we are going to learn how to Specify the type in the TypeScript arrow function. Below are the approaches used to Specify the return type in the TypeScript arrow function: Table of Content Explicit Return Type AnnotationType InferenceFunction D
2 min read
What are Arrow/lambda functions in TypeScript ?
The Arrow/ lambda function is a concise form of a normal function in Typescript. Arrow functions are also known as lambda functions. We use "=>" (arrow symbol) in the arrow function and we do not use the 'function' keyword. We can use this method when we want our code to be short and not call the function each time. Syntax1. Arrow function havin
2 min read
Does JavaScript have higher precedence than CSS ?
While working on the front-end part of your project, CSS plays a major role in defining the styles for your web page. With the help of knowledge in DOM (Document Object Model) and JavaScript, it is possible to change styles for your web page using script files. In this article, we will discuss the precedence of JavaScript with respect to CSS in ter
2 min read
Javascript Program For Pointing To Next Higher Value Node In A Linked List With An Arbitrary Pointer
Given singly linked list with every node having an additional "arbitrary" pointer that currently points to NULL. Need to make the "arbitrary" pointer point to the next higher-value node. We strongly recommend to minimize your browser and try this yourself first A Simple Solution is to traverse all nodes one by one, for every node, find the node whi
4 min read
Arrow operator in ES6 of JavaScript
ES6 has come with various advantages and one of them is the arrow operator. It has reduced the function defining code size so it is one of the trending questions asked in the interview. Let us have a deeper dive into the arrow operator's functioning. Syntax: In ES5 a function is defined by the following syntax: function functionName(arg1, arg2….) {
4 min read
How to disable arrow key in textarea using JavaScript ?
Given an HTML element containing the <textarea> element and the task is to disable scrolling through arrow keys with the help of JavaScript. Approach 1: Add an event listener onkeydown on the window.If the event happens then check if the keys are arrow or not.If arrow key is pressed then prevent its default behaviour. Example: This example im
2 min read
JavaScript Detecting the pressed arrow key
Sometimes we need to detect the keys and sometimes even detect which keys were pressed. To detect which arrow key is pressed we can use JavaScript onkeydown event. Detecting the pressed arrow key using onkeydown EventThe DOM onkeydown Event in HTML occurs when a key is pressed by the user. Syntax:object.addEventListener("keydown", myScript);Example
2 min read
How to store JavaScript functions in a queue and execute in that order?
In this article, the task is to execute the functions in the order defined in the queue with the help of JavaScript. There are two approaches that are discussed below. Approach 1: Declare the functions and use the array push() method to push the functions in the array. Later traverse the array and execute the functions one by one. Example: This exa
2 min read
React Suite Tooltip Hide Arrow Indicator
React suite is a library of React components, sensible UI design, and a friendly development experience. It is supported in all major browsers. It provides pre-built components of React which can be used easily in any web application. In this article, we’ll learn about React suite Tooltip Hide Arrow Indicator. The tooltip component allows users to
3 min read
How to remove arrow in dropdown in Bootstrap ?
Dropdowns are one of the important components that are an integral part of any web application. Bootstrap provides its own interactive version of this component. Bootstrap dropdowns are toggled by clicking, not hovering as it was an intentional design decision. To use Dropdowns in a web project, include Popper.js into the project. Every Bootstrap d
2 min read
How to move an element to left, right, up and down using arrow keys ?
The task is to move an element to left, right, up and down using arrow keys in jquery, we can use the jQuery keydown() method along with the .animate() method. The keydown() method triggers the keydown event whenever User presses a key on the keyboard. Syntax: $(selector).keydown(function) Approach: The .keydown() method is to used check whether an
3 min read
How to decorate list bullets in arrow using CSS ?
Given a list of items and the task is to customize the bullet style of the list and replace it with the arrow. Method 1: By Unicode Character First, we will turn off the default bullet style of the list. Then We will insert Unicode of the arrow character in the content property in the "li::before" selector. Example: <!DOCTYPE html> <html
2 min read
How to create Left arrow icon using jQuery Mobile ?
jQuery Mobile is a web-based technology used to make responsive content that can be accessed on all smartphones, tablets, and desktops. In this article, we will be making a left arrow icon using jQuery Mobile. Approach: First, add jQuery Mobile scripts needed for your project. <link rel=”stylesheet” href=”http://code.jquery.com/mobile/1.4.5/jque
1 min read
three90RightbarBannerImg