Understanding Higher Order Functions in JavaScript: A Beginner’s Guide

TUSHAR KANJARIYA
6 min readApr 10, 2023

--

Let’s get an understanding of Higher Order Functions in JavaScript with Examples.

Understanding Higher Order Functions in JavaScript: A Beginner’s Guide | Tushar Kanjariya
Understanding Higher Order Functions in JavaScript: A Beginner’s Guide

Hello Developers 👋,
JavaScript is a powerful and versatile programming language, and one of its most important features is the ability to use higher-order functions. Higher-order functions are functions that take one or more functions as arguments and/or return a function as a result.

Higher Order Functions are an essential concept in JavaScript and functional programming. They allow you to write more flexible, modular, and efficient code by taking functions as arguments and/or return functions as values. In this beginner’s guide, we will explore what Higher Order Functions are, why they are important, and some examples of how to use them in JavaScript.

👉 What are Higher Order Functions?

In JavaScript, a higher-order function is a function that takes another function as an argument or returns a function as its result. These functions are sometimes referred to as “function factories” because they create new functions.

Here’s an example of a higher order function that takes another function as an argument:

function multiplyByTwo(num) {
return num * 2;
}

function higherOrderFunction(fn, num) {
return fn(num);
}

higherOrderFunction(multiplyByTwo, 5); // returns 10

In this example, the higherOrderFunction function takes two arguments: fn, which is a function, and num, which is a number. The fn argument is then called with the num argument, and the result is returned.

👉 Why Use Higher Order Functions?

Higher-order functions are useful because they allow you to create more flexible and reusable code. By passing functions as arguments, you can create functions that can be customized for different scenarios.

For example, let’s say you have an array of numbers and want to create a new array containing each number’s square.

You could write a function that does this like so:

function square(num) {
return num * num;
}

function squareArray(arr) {
const result = [];

for (let i = 0; i < arr.length; i++) {
result.push(square(arr[i]));
}

return result;
}

const myArray = [1, 2, 3, 4, 5];
squareArray(myArray); // returns [1, 4, 9, 16, 25]

This works fine, but what if you want to create a new array containing each number’s cube? You could write another function that does this, but that would be duplicating a lot of code. Instead, you could pass a function as an argument to the squareArray function:

function cube(num) {
return num * num * num;
}

function squareArray(arr, fn) {
const result = [];

for (let i = 0; i < arr.length; i++) {
result.push(fn(arr[i]));
}

return result;
}

const myArray = [1, 2, 3, 4, 5];
squareArray(myArray, square); // returns [1, 4, 9, 16, 25]
squareArray(myArray, cube); // returns [1, 8, 27, 64, 125]

Now you can reuse the squareArray function with different functions to create arrays with different calculations.

They allow you to write more reusable, flexible, and concise code, making your JavaScript code more efficient and easier to maintain.

Here are some ways Higher Order Functions can improve your JavaScript code:

▹ Re-usability

Higher Order Functions allow you to write code that can be reused in different parts of your application. You can pass different callback functions to the same Higher Order Function, allowing you to reuse the code without having to duplicate it.

This makes your code more modular, reducing code redundancy, and making it easier to maintain and modify.

▹ Code Flexibility

Higher Order Functions provide a way to make your code more flexible by allowing you to pass different functions with different functionalities as arguments. You can pass any function that matches the signature of the required function, making your code more flexible and adaptable to changes.

▹ Code Conciseness

Higher Order Functions can help you write code that is more concise and easier to read. They allow you to encapsulate complex functionality into a single function, making your code more readable and easier to understand. This is especially useful when you need to perform the same operation on multiple objects or when working with large data sets.

▹ Asynchronous Code

Higher Order Functions can also be used to write asynchronous code. They allow you to perform an operation on a set of data asynchronously, without blocking the main thread. This is useful when working with large data sets or when performing long-running operations.

Functional Programming

Higher Order Functions are a key concept in functional programming, which is a programming paradigm that emphasizes the use of functions to solve problems. Functional programming promotes the use of Higher Order Functions because they allow you to write code that is more modular, reusable, and easier to test.

You can learn more about Functional Programming in this Article.

👉 Common Higher Order Functions in JavaScript

JavaScript provides several built-in higher-order functions that you can use to work with arrays:

Example 1: Map Function

The map function is a higher-order function that takes a callback function and applies it to each element of an array, returning a new array of the results.

The callback function receives the current value, index, and array as arguments. This method is used for transforming an array into a new array without modifying the original.

For Example:

const numbers = [1, 2, 3, 4, 5];

const doubledNumbers = numbers.map(function(number) {
return number * 2;
});

console.log(doubledNumbers); // [2, 4, 6, 8, 10]

In this example, we passed a function that takes a number as an argument and returns the result of multiplying that number by 2 to the map function. The map function then applied this function to each element in the numbers array and returned a new array with the doubled values.

Example 2: Filter Function

The filter function is another Higher Order Function that takes a callback function and applies it to each element of an array, returning a new array containing only the elements for which the callback function returns true.

The callback function receives the current value, index, and array as arguments.

For Example:

const numbers = [1, 2, 3, 4, 5];

const evenNumbers = numbers.filter(function(number) {
return number % 2 === 0;
});

console.log(evenNumbers); // [2, 4]

In this example, we passed a function that takes a number as an argument and returns true if the number is even, and false otherwise, to the filter function. The filter function then applied this function to each element in the numbers array and returned a new array containing only the even numbers.

Example 3: Sort Function

The sort method is a Higher Order Function that sorts the elements of an array according to a sorting function. The sorting function takes two arguments, and it returns a value that indicates the order of the two elements.

If the sorting function returns a negative value, the first element is sorted before the second, if it returns a positive value, the second element is sorted before the first.

For Example:

const numbers = [4, 2, 1, 5, 3];

const sortedNumbers = numbers.sort(function(a, b) {
return a - b;
});

console.log(sortedNumbers); // [1, 2, 3, 4, 5]

Example 4: Reduce Function

The reduce method is a Higher Order Function that takes a callback function and applies it to each element of an array, reducing the array to a single value.

The callback function receives two arguments, an accumulator and the current value. The accumulator is initialized to an initial value, and the callback function returns a new accumulator value for each iteration.

For Example:

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce(function(accumulator, number) {
return accumulator + number;
}, 0);

console.log(sum); // 15

in this example, We passed 1 function that contains 2 parameters accumulator and number.

accumulator is initially set to 0 and after running the code it will every time contains a new calculated sum of array index values.

Conclusion

In conclusion, Higher Order Functions are an essential part of JavaScript programming, allowing you to write more efficient, modular, and maintainable code. By using Higher Order Functions, you can make your code more reusable, flexible, and concise, improving the overall quality of your JavaScript code.

Thanks for Reading 🙏😇

--

--

TUSHAR KANJARIYA

Working as a Full Stack Developer in @Simform and UI/UX Designer By Hobby