High Order Function vs. First Class Function Explained in JavaScript
April 29th, 2025 | By Ezekiel Lawson | 14 min read
JavaScript functions are tools that help you get things done in your programs. There are two main concepts about functions: first-class functions and higher-order functions. These may sound a bit technical, but they’re easy to understand once you know the basics. First-class functions are the foundation, and higher-order functions build on them to make our programs smarter and more efficient.
In this article, you will learn what they mean and how they’re different, and see simple examples to help you understand how they work. Higher-order functions and first-class functions are at the heart of JavaScript's functional programming style. They help developers create cleaner, reusable code. Mastering these concepts will simplify complex tasks and make your projects easier to manage and maintain.
Now that you have a quick introduction to why these two concepts are important in JavaScript, you might still wonder what they are and how to use them. Let’s break it down, starting with high-order functions and how you can apply them in your projects.
Defining High-Order Function
A higher-order function in JavaScript is a function that either takes other functions as arguments or returns a function after completing its task. These functions, often called callbacks, enable good operations and flexibility in code.
Common examples of higher-order functions include `map`, `filter`, and `reduce`. These functions accept another one as an argument, allowing for simple array operations.
Using `**map**` method
Transforming an array of names to uppercase:
const names = ['Mike', 'John', 'Rita'];
const uppercasedNames = names.map(name => name.toUpperCase());
console.log(uppercasedNames);
Code Output:
['MIKE', 'JOHN', 'RITA']
Using `filter` method
This code example filters out numbers less than or equal to 10:
const numbers = [5, 12, 8, 20, 7, 9, 11, 13, 20,];
const smallNumbers = numbers.filter(num => num <= 10);
console.log(smallNumbers);
Code Output:
[5, 8, 7, 9]
Using `reduce` method
Finding the product of all numbers in an array: The `reduce` method combines all array elements into a single value. It multiplies all numbers together, starting with `1` as the initial value. The final result, 24, is the product of `2 3 4` :
const nums = [2, 3, 4];
const product = nums.reduce((acc, curr) => acc * curr, 1);
console.log(product);
Code Output:
24
The code examples above introduce higher-order functions in JavaScript. You have likely encountered many of these methods in your projects as a developer. The name might sound a bit complicated, but it’s just a fancy way of describing something that’s a basic part of how JavaScript works.
Defining First-Class Function
First-class function is one that’s treated just like any other value in JavaScript. This means you can assign it to a variable, pass it as an argument to another function, return it from a function, or even store it in an array or object. This makes it easy to use functions in many different ways.
I have mentioned a few examples of what you can do with first-class functions. Now, let’s take a look at some code examples to see them in action.
Assign Functions to Variables:
const greetUser = () => "Hello, John Doe";
console.log(greetUser());
Code Output:
Hello, John Doe
Pass Functions as Arguments to Other Functions:
const greet = () => "Hello!";
const logMessage = (messageFunction) => console.log(messageFunction());
logMessage(greet);
The `greet` function is passed as an argument to `logMessage`. Inside `logMessage`, the passed function (`messageFunction`) is called. This example demonstrates how functions can be passed as arguments to other functions in JavaScript.
Code Output:
Hello!
Return Functions from Other Functions:
const createGreeter = (name) =>
{ return () => `Hello, ${name}!`;
}
const greetJohn = createGreeter("John");
console.log(greetJohn());
Code Output:
Hello John
The `createGreeter` function returns a new function that uses the name parameter. When `createGreeter("John")` is called, it returns a function that greets "John". This example shows how functions can return other functions. This introduction is becoming clearer, but the most interesting part still lies ahead, as it explores their differences.
Differences: Higher-Order Function vs. First-Class Function
Understanding the difference between higher-order functions and first-class functions is essential for mastering JavaScript. Although they are closely related, each serves a distinct role and helps you understand different functions used in the language.
Higher-Order Function
A high-order function is a function designed to work with other functions. It does this by either accepting one or more functions as arguments to carry out specific tasks or by returning a new function with a new behavior. It focuses on how functions interact with other functions. These include the previous methods we talked about in the definition, as well as functions that create closures or handle callbacks.
Code Example of Higher-Order Function
Let's consider a simple real-life business example to clarify this concept. Imagine you own a business offering discounts of 10% and 20%, and you need to calculate the discounted price for a customer's total bill. To achieve this, you create a function called `createDiscount`. This function takes an argument, `discountPercentage`, and returns a new function that calculates the final price based on any given `totalPrice`. For instance, calling `createDiscount(10)` generates a function that applies a 10% discount, while `createDiscount(20)` produces a function for a 20% discount. This reusable approach simplifies calculating discounts for various percentages.
function createDiscount(discountPercentage) {
return function(totalPrice) {
return totalPrice - (totalPrice * discountPercentage / 100);
};
}
const tenPercentDiscount = createDiscount(10);
const twentyPercentDiscount = createDiscount(20);
console.log(tenPercentDiscount(100)); // Output: Missing comment
console.log(twentyPercentDiscount(200)); // Output: 160 (20% off $200)
Code Output:
(10% off $100) = $90
(20% off $200) = $160
Remember when I talked about functions returning other functions in the beginning? That concept applies perfectly here. For instance, when you call the returned function `tenPercentDiscount(100)`, it calculates the discounted price by subtracting 10% from the total amount. This approach simplifies the code and eliminates redundancy, allowing you to reuse the same discount-calculation logic for different percentages efficiently.
Designed to enable advanced operations and patterns, such as currying, composition, and event handling. They are a practical implementation of functional programming principles.
First-Class Function
In JavaScript, a first-class function is treated as a variable, meaning it can be assigned to another variable or passed as an argument. It highlights the capability of functions as values and is a foundational concept that enables higher-order functions.
Let me show you a quick code example of how it enables higher-order functions.
Code Example: Filtering and transforming an array of users
Imagine you have an array of user objects and want to filter, transform, and display the result. You can use first-class functions to pass the logic for filtering and transforming as arguments to higher-order functions like `map()` and `filter()`.
The functions `isOlderThan21` and `formatName` are passed as arguments to the `filter()` `map()` methods, respectively. This demonstrates how JavaScript treats functions as values that can be assigned to variables or passed around. It also highlights how first-class functions enable us to abstract code logic, making our code more reusable.
const users = [
{ name: 'Alice', age: 20 },
{ name: 'Mark', age: 30 },
{ name: 'Joseph', age: 35 },
{ name: 'David', age: 40 }
];
const isOlderThan21 = (user) => user.age > 21;
const formatName = (user) => `${user.name} (${user.age} years old)`;
const adultUsers = users
.filter(isOlderThan21)
.map(formatName);
console.log(adultUsers);
Code Output
['Mark (30 years old)', 'Joseph (35 years old)', 'David (40 years old)']
In the previous example, I used the `filter()` and `map()` methods, and you might be wondering why. These methods are part of higher-order functions because they can take other functions as arguments. However, the main focus of the example was to show how first-class functions enable higher-order functions.
First-class functions mean that you can treat functions like any other value in JavaScript. You can:
Assign a function to a variable.
Pass a function as an argument to another function.
Return a function from another function.
The example demonstrates this ability. To make it clearer, higher-order functions (like `filter()` and `map()`) are only possible because JavaScript allows functions to be treated as values.
Here’s a simpler example that directly highlights first-class functions in action:
This code demonstrates how JavaScript treats functions as first-class citizens. First, a function (`sayHello`) is defined and assigned to a variable, allowing it to be stored like any other value. Next, another function (`greetUser`) is created, which takes a function and a user name as arguments. When `greetUser` is called with `sayHello` and the name `Unice Michael`, it executes the `sayHello` function with `Unice Michael` as the input, returning the greeting `Hello, Unice Michael`.
const sayHello = function(name) {
return `Hello, ${name}!`;
};
function greetUser(greetingFunction, userName) {
return greetingFunction(userName);
}
const message = greetUser(sayHello, "Unice Michael");
console.log(message);
Finally, the result is stored in a variable called `message` and displayed in the console when called. This example shows how functions can be passed as arguments to other functions, making the code more flexible and reusable. Below is an output of the above code:
Code Output
"Hello, Uncle Michael"
First-Class Functions can be used as event handlers, which means a function can be triggered by events such as a mouse click or a key press. This makes the program more interactive and user-friendly.
As a new developer, understanding first-class functions is an important step in improving your coding skills. First-class functions offer benefits like code reusability and help you follow the "Don't Repeat Yourself" principle, reducing code redundancy.
Key Differences between First-Class and Higher-Order Functions
Function Usage:
A first-class function lets you create functions that can be reused and stored for later use, making your code more flexible.
A higher-order function helps you build more complex tasks by combining simple functions or changing how existing functions behave.
Function Purpose:
First-class functions allow you to treat functions like other data types (such as numbers or strings). You can store them, pass them around, and change them as needed.
Higher-order functions make it possible to perform more complex tasks by using functions as arguments or returning them, often to change or add to how things work in your code.
Common Misunderstandings
While first-class and higher-order functions are good features in JavaScript, they are often misunderstood, especially by beginners. These misunderstandings can lead to confusion about their purpose and proper use. Let’s clear up some of the most common misconceptions:
Most people think functions are only meant for running code, but in JavaScript, functions are treated like values you can assign to variables, pass as arguments, and return from other functions.
Some developers believe first-class functions only involve passing functions as arguments, but they also include storing functions in variables, arrays, or objects and returning functions from other functions.
Some see higher-order functions as too advanced or difficult for beginners, but this function can simplify code and reduce repetitive logic once understood.
It's often assumed that first-class functions are only useful in functional programming, but they are a core feature of JavaScript and benefit many programming styles.
Lastly, it’s assumed that higher-order functions always improve performance, but sometimes, they can introduce overhead if used without a clear purpose.
Understanding first-class functions and higher-order functions in JavaScript is important for writing clean and organized code. First-class functions let you treat functions like objects, giving you more flexibility in using them. Higher-order functions take this even further, allowing you to pass functions as arguments to other functions or return them as results.
Jscrambler
The leader in client-side Web security. With Jscrambler, JavaScript applications become self-defensive and capable of detecting and blocking client-side attacks like Magecart.
View All ArticlesMust read next
Understanding Generator Function in Javascript
This article introduces beginners to generator functions, explains their importance, and explores how they streamline complex tasks like lazy evaluation and creating custom iterables.
September 24, 2024 | By Ezekiel Lawson | 12 min read
Enhancing JavaScript Security: Best Practices, Vulnerabilities, and Third-Party Risks
The widespread use of JavaScript makes it a focal point for cyber threats, exposing web applications to various security risks.
June 18, 2024 | By Antonello Semeraro | 10 min read
