Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Difference between First-Class and Higher-Order Functions in JavaScript
Next article icon

JavaScript Higher Order Functions

Last Updated : 15 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A higher-order function is a function that does one of the following:

  • Takes another function as an argument.
  • Returns another function as its result.

Higher-order functions help make your code more reusable and modular by allowing you to work with functions like any other value.

JavaScript
function fun() {     console.log("Hello, World!"); } function fun2(action) {     action();     action(); }  fun2(fun); 

In this example

  • fun2 is a higher-order function because it takes another function (action) as an argument.
  • It calls the action function twice.

Popular Higher Order Functions in JavaScript

1. map

The map function is used to transform an array by applying a callback function to each element. It returns a new array.

JavaScript
const n = [1, 2, 3, 4, 5]; const square = n.map((num) => num * num); console.log(square); 
  • map applies the callback (num) => num * num to each element of numbers.
  • A new array is returned where each element is the square of the original

2. filter

The filter function is used to create a new array containing elements that satisfy a given condition.

JavaScript
const n = [1, 2, 3, 4, 5]; const even = n.filter((num) => num % 2 === 0); console.log(even); 
  • The callback (num) => num % 2 === 0 filters out elements not divisible by 2.
  • The resulting array contains only even numbers.

3. reduce

The reduce function accumulates array elements into a single value based on a callback function.

JavaScript
const n = [1, 2, 3, 4, 5]; const sum = n.reduce((acc, curr) => acc + curr, 0); console.log(sum);  
  • The callback (acc, curr) => acc + curr adds all elements.
  • 0 is the initial value of the acc.

4. forEach

The forEach function executes a provided function once for each array element.

JavaScript
const n = [1, 2, 3]; n.forEach((num) => console.log(num * 2)); 
  • forEach performs the side effect of printing each element multiplied by 2.
  • It does not return a new array like map.

5. find

The find function returns the first element in the array that satisfies a given condition.

JavaScript
const n = [1, 2, 3, 4, 5]; const fEven = n.find((num) => num % 2 === 0); console.log(fEven); 
  • The callback (num) => num % 2 === 0 finds the first even number.
  • If no element satisfies the condition, it returns undefined.

6. some

The some function checks if at least one array element satisfies a condition.

JavaScript
const n = [1, 2, 3, 4, 5]; const hasNeg = n.some((num) => num < 0); console.log(hasNeg); 
  • The callback (num) => num < 0 checks for negative numbers.
  • It returns true if any element passes the condition, false otherwise.

7. every

The every function checks if all array elements satisfy a condition.

JavaScript
const n = [1, 2, 3, 4, 5]; const allPos = n.every((num) => num > 0); console.log(allPos) 
  • The callback (num) => num > 0 checks if all numbers are positive.
  • It returns true only if all elements pass the condition.

Advanced Techniques with Higher Order Functions

1. Function Composition

Function composition is the process of combining multiple functions to create a new function. The composed function applies multiple operations in sequence.

JavaScript
function add(x) {     return x + 2; } function mul(x) {     return x * 3; }  function compose(f, g) {     return function(x) {         return f(g(x));   }; } var res = compose(add, mul)(4); console.log(res); 
  • compose combines add and multiply, so the output of multiply is passed as input to add.
  • The result of compose(add, mul)(4) is 14 because 4 is first multiplied by 3 and then 2 is added.

2. Currying

Currying transforms a function that takes multiple arguments into a series of functions that each take one argument. This allows partial application of the function.

JavaScript
function mul(x) {     return function(y) {         return x * y;   }; } var mul = mul(2); console.log(mul(5)); 
  • The multiply function is curried, returning a new function each time it is called with an argument.
  • multiplyBy2 is a partially applied function that multiplies any given number by 2.

3. Memoization

Memoization is a technique where function results are cached so that repeated calls with the same arguments return faster. This is particularly useful for expensive function calls.

JavaScript
function memoize(func) {     var cache = {};     return function (arg) {         if (cache[arg]) {             return cache[arg];         } else {             var res = func(arg);             cache[arg] = res;             return res;         }     }; } function slow(num) {     console.log("Computing...");     return num * 2; }  var fast = memoize(slow); console.log(fast(5)); // Computing... 10 console.log(fast(5)); // 10 (cached) 
  • memoize caches the results of slowFunction calls. The second time fast(5) is called, the result is fetched from the cache, avoiding recomputation.
  • This optimization improves performance by saving on redundant calculations.

Use case's of higher order functions

1. Passing Functions as Arguments

In the following example, we define a Higher-Order Function called greet that accepts a callback function as an argument and executes it

JavaScript
function greet(name, callback) {     console.log("Hello, " + name);     callback(); }  function sayGoodbye() {     console.log("Goodbye!"); }   //Driver Code Starts{ greet("Ajay", sayGoodbye);  //Driver Code Ends } 
  • Function as Argument: greet accepts another function (e.g., sayGoodbye) as a callback, demonstrating the ability to pass functions as arguments.
  • Sequence Control: It first logs a greeting message and then executes the callback, showing how actions can be performed in a specific order.
  • Modularity and Reusability: By separating the greeting and goodbye actions, the pattern allows flexibility and reusability, enabling different callbacks to be passed as needed.

2. Returning Functions from Functions

Higher-order functions can also return a function. This enables the creation of more dynamic behavior

JavaScript
function mul(factor) {     return function(num) {         return num * factor;     }; }   //Driver Code Starts{ const mul2 = mul(2); console.log(mul2(5)); const mul3 = mul(3); console.log(mul3(5));  //Driver Code Ends } 
  • Function Factory: mulBy returns a new function based on the provided factor, demonstrating the ability to create dynamic, parameterized functions.
  • Closure in Action: The returned function uses the captured factor to perform multiplication, showcasing the power of closures to retain access to external variables.
  • Reusability and Customization: This pattern simplifies creating reusable multipliers (e.g., mul2, mul3), enabling efficient and customizable solutions with minimal effort.

3. Array Method map() as a Higher-Order Function

JavaScript array methods such as map(), filter(), and reduce() are excellent examples of higher-order functions. These methods take callback functions as arguments and provide powerful ways to manipulate arrays.

JavaScript
const a = [1, 2, 3, 4, 5]; const double = a.map(function(n) {     return n * 2; });  console.log(double);  
  • Array Transformation: map() applies a callback function to each array element, returning a new array with transformed values while keeping the original array unchanged
  • Immutability: By not mutating the original array, map() supports immutable data handling, which is key to predictable and safer code.
  • Declarative Iteration: It abstracts the iteration logic, promoting a declarative programming style that focuses on what should be done rather than how.

4. Array Method filter() as a Higher-Order Function

The filter() method is another array function that is a higher-order function. It filters the elements of an array based on a condition provided by the callback function.

JavaScript
const a = [1, 2, 3, 4, 5]; const even = a.filter(function(n) {     return n % 2 === 0; });  console.log(even); 
  • Conditional Filtering: filter() applies a callback function to test each element, returning a new array containing only those that meet the specified condition.
  • Immutability: It leaves the original array unchanged, ensuring the integrity of the source data while providing filtered results.
  • Customizable and Reusable: filter() is highly flexible, allowing easy customization for different conditions to extract specific subsets of data.

5. Array Method reduce() as a Higher-Order Function

The reduce() method is a powerful higher-order function used to reduce an array to a single value.

JavaScript
const n = [1, 2, 3, 4, 5]; const sum = n.reduce(function(acc, curr) {     return acc + curr; }, 0); console.log(sum); 
  • Accumulation: reduce() processes each element of the array, accumulating a single value (e.g., sum, product) based on the provided callback function.
  • Initial Value and Flexibility: The second argument (e.g., 0) sets the initial value for the accumulator, ensuring consistent results and allowing for flexible aggregation.
  • Versatility: It can be used for a wide range of tasks, such as summing values, calculating products, or even more complex operations like flattening arrays.

Next Article
Difference between First-Class and Higher-Order Functions in JavaScript

D

dpsingh
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-functions

Similar Reads

  • 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
    4 min read
  • Difference between First-Class and Higher-Order Functions in JavaScript
    Understanding the difference between first-class and higher-order functions in JavaScript is 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 importa
    3 min read
  • TypeScript Functions Type
    TypeScript function types define the structure of a function, including its parameter types and return type, ensuring consistent and type-safe usage. Help validate the types of parameters passed to a function.Ensure the function returns the expected type.Improve code clarity and prevent runtime erro
    6 min read
  • What is the first class function in JavaScript ?
    First-Class FunctionA programming language is said to have First-class functions if functions in that language are treated like other variables. So the functions can be assigned to any other variable or passed as an argument or can be returned by another function. JavaScript treats function as a fir
    2 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 ar
    2 min read
  • Operator precedence in JavaScript
    Operator precedence refers to the priority given to operators while parsing a statement that has more than one operator performing operations in it. Operators with higher priorities are resolved first. But as one goes down the list, the priority decreases and hence their resolution. ( * ) and ( / )
    2 min read
  • TypeScript Anonymous Functions Type
    In TypeScript, an Anonymous Function Type defines a function without a specific name, specifying parameters and return types. This allows for flexible and reusable function definitions, enabling the assignment of functions to variables and the use of type annotations for parameters and return values
    3 min read
  • TypeScript Function Type Expressions
    In this article, we are going to learn about TypeScript Function Type Expressions in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, a function type expression represents the type of a function, including its parameter types
    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 followin
    6 min read
  • Kotlin Higher-Order Functions
    Kotlin language has superb support for functional programming. Kotlin functions can be stored in variables and data structures, passed as arguments to and returned from other higher-order functions. Higher-Order Function - In Kotlin, a function which can accept a function as parameter or can return
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences