Understanding Higher Order Functions in JavaScript

Higher order functions

In programming, functions play a very crucial part. A function is an organized block of code that is created for a specific task. It can also accept and return values. The main purpose of using functions is code reusability. There is a lot about functions in JavaScript. In JavaScript, functions are higher-order functions. To understand this term – “Higher-order functions”, we need to understand some basic concepts related to JavaScript functions. So in this article, we will discuss everything related to higher-order functions in JavaScript.

Functions in JavaScript

Observe the following code.

function demo(){
    console.log("This is a demo function")
}
demo()

This is a very basic example of a JavaScript function. The name of the function is “demo” and its prints “Hello World!” in the console. But we can do a lot more with this function. For example, we can assign it to a variable, or pass it to another function as a parameter. This is possible because JavaScript is a functional programming language.

Being a functional programming language, JavaScript treats functions as objects. The following code proves it.

function demo(){
    console.log("This is a demo function")
}

demo.property = "This is a property"

console.log(demo.property)

Just like we add a property to a JavaScript object, a property is added to the “demo” function. let’s execute the code.

Demo function

Well, it proves that functions in JavaScript are treated as JavaScript objects, however, it is recommended not to use the above approach in real-time. This was just a demonstration.

Like numbers and strings, we can assign functions to variables, pass them as a parameter, and even return them from another function. So basically we can do everything with JavaScript functions that is possible with strings, numbers, etc. JavaScript functions are treated as an object, or we can say as first-class citizens. This is the reason why JavaScript functions are called “Firs-class functions”.

Let’s go through some examples.

const demo = function(){
    console.log("Hello World!")
}

demo()

In the above code, a function is assigned to the variable named “demo”.

const demo2 = function(){
    console.log("Hello World!")
}

const demo1 = function(fun){
    fun()
}

demo1(demo2)

This time, “demo2” is passed as a parameter to “demo1” and then it is called inside it. Let’s execute and see the result.

Demo 2

It is necessary to understand these few concepts related to JavaScript Functions. Now, let’s discuss higher-order functions.

Higher-order functions

In simple words, a function that operates on another function is called a higher-order function. The way of operating can differ. The function can be passed to it or returned as an output.

There are few in-built higher-order functions in JavaScript. For example, the “map” function.

The map function is one of the most commonly used in-built function in JavaScript. It works on an array and creates a new array from it. The important part is that it operates on a function, thus making it a higher-order function. Let’s understand with the help of an example.

const double = function(element){
    return element * 2
}

var arr1 = [1, 2, 3, 4, 5]
var arr2 = arr1.map(double)

The above code explains the concept of higher-order functions in the simplest way. The “arr1” has five elements. The map function is used to create a new array from “arr1” by operating on the “double” function.

var arr2 = arr1.map(double)

The “double” function is passed as a parameter to the map function. Here, every element of “arr1” is passed to the “double” function, which in turn is returning its double value.

Demo 3

So the main point is how the map function is operating on another function that is passed to it as a parameter. Let’s try another in-built higher-order function, i.e. “filter. The filter function also creates a new array, but only those elements are added to the new array that passes the condition.

const checkEven = function(element){
    return element % 2 == 0
}

arr1 = [1, 2, 3, 4, 5]
arr2 = arr1.filter(checkEven)

console.log(arr2)

In the above code, the “checkEven” has a condition to the check if a number is even or not. The filter function is operating on the “checkEven” function to create a new arr (arr2) from arr1.

We can also create our own higher-order functions. Observe the following code.

const checkOdd = function(arr, fun){
    var newArr = []
    for(var i = 0; i < arr.length; i++){
        if(arr[i] % 2 != 0){
            newArr.push(fun(arr[i]))
        }
        else{
            newArr.push(arr[i])
        }
    }

    return newArr
}

const add = function(element){
    return element + 1
}

arr = [1, 2, 3, 4, 5]
const newArr = checkOdd(arr, add)

console.log(newArr)

In the above code, the function named “checkOdd” is a higher-order function. The “checkOdd” functions have two parameters – an array and a function. The function that is passed to it is named as “add”. Now, this “checkOdd” function iterates over the array (arr) and check if the element is odd or even, then appends it to another array named “newArr”. If the element is odd, then it is passed as a parameter to the “add” function (which was passed as a parameter to the “checkOdd” function). Then, the “add” function returns the element by adding one to it. At the end, when the iteration is over, the new array is returned.

So the “checkOdd” is operating on another function, “add” that is passed as a parameter to it. Thus, it is a higher-order function.

Wrapping it up

The concept of higher-order function is a bit confusing. But in this article, we tried to keep it as simple as we can so that the beginners can catch the meaning of higher-order functions properly. There are few in-built higher-order functions in JavaScript, such as map that we discussed with a simple example. Other in-built higher-order functions are reduce, filter, etc. We can also create higher-order functions manually. We also discussed this with a simple example. Try to create your own higher-order functions. It will surely help you understand the working of higher-order functions more efficiently.

Image Credits: Photo by Caspar Camille Rubin on Unsplash.

More Similar Posts

Menu