The Top Most Useful Higher-Order Functions for JavaScript Developers

The Top Most Useful Higher-Order Functions for JavaScript Developers

A higher-order function is a function that takes a function as an input and/or returns a function. In this article, I'll be looking at the topmost useful higher-order functions for JavaScript developers. As always, there are many higher-order functions than the ones I've chosen to highlight. The aim of this post is not to cover every single one of them (that would be pretty boring). Instead, I want to look at the higher-order functions that I find myself using all the time - in every project.

What is a higher-order function?

In computer science, a higher-order function is a function that works as the following: one takes one or more functions as an input, returns a function as output, or both. Higher-order functions are an important concept in functional programming.

The current trend in front-end development (and there’s no reason why this should change in back-end development as well) is to separate the rendering and data-fetching logic from the styling logic. Given that rendering is subject to change on the fly (it’s not a static process, and changes to the site could trigger different code paths, for instance), this makes sense. However, there are scenarios where you still want to work with data.

For example, a UX designer, who needs to know some information about the current page to be able to design a decent user experience. In this case, she/ he might come up with the idea to fetch some data from a server (in the form of cookies). This might be a more traceable and gatherable method than if we had put the data into the database.

In modern frameworks (especially React and Angular), you can reuse this same functionality by putting the data in local storage or using an API, and props (whatever) will be passed to your component as arguments (there’s a debug prop that can be useful here as well).

If you are looking to become a Javascript Developer? Check out the Javascript Certification Course and enhance your career.

Why use them?

Higher-order functions are functions that take functions as arguments or return functions as values. This article explains why higher-order functions make it easier to create reusable code and what patterns can be used to create higher-order functions.

The idea of a higher-order function is to take an arbitrary number of functions as inputs and output functions as output. A common use of functions in JavaScript is to create specific parts of an interactive application. A static piece of HTML that we can hide or show some information. A piece of JavaScript automatically shows a page when a user enters a URL, when a user clicks a button or enters a piece of data into a form, we usually want to react to it as part of a separate process. We’d also like to provide feedback to the user, for example, if they’ve entered a wrong email address or password or have entered something invalid. Sometimes, though, we need to do these things together with the main program so that the user experience doesn’t break.

Topmost useful higher-order functions for JavaScript developers

There are many higher-order functions in JavaScript. They are extremely useful for developers because they can make the code more efficient and easier to read. Here are the top 5 most useful higher-order functions:

1. Map()

The first function is a map and it takes a list of values and returns a new list by applying a function to each value in the original list.

The first function is called map() and it takes a list of values and returns a new list by applying a function to each value in the original list.

The map takes a function as an argument and returns a new list, with one element for each element in the original list. In our case, we pass it a list of numbers (that is, an array), and it returns a new array that has each element for the index of that corresponding number in the original array.

Syntax:

array.map(function(currentValue, index, arr), thisValue)

An example usage would be:

var numbers = [4, 9, 16, 25]; var x = numbers.map(Math.sqrt) document.getElementById("demo").innerHTML = x;

a map will also accept a second parameter, target, which can be an array that needs to be filtered (for example, you can define a custom object that holds all the products of a certain store or contains all the emails in an address).

In the previous example, when an item was a product from the CVS store, it only contained elements that were part of a specific address.

Now, with a target of [{ address: [ { street: ‘123 Main Street’, city: ‘New York’ }]}], map will return a new array with one item per address in the set. (Using the items argument can be useful but is less useful for us because the target function returns a new array containing all the items in the set. You can read more about arrays in my last post.)

2. Filter()

The second function is called and it takes a list of values and returns a new list containing only those values for which the provided function evaluates to true. This allows us to remove unwanted data from our lists (i.e., all the data that we don't want).

Syntax:

array.filter(function(currentValue, index, arr), thisValue)

Example:

var ages = [32, 33, 16, 40];

function checkAdult(age) { return age >= 18; }

function myFunction() { document.getElementById("demo").innerHTML = ages.filter(checkAdult); }

This function is similar to the map() function in that it applies a function to all members of a list, but it doesn't create a new list. The filter() function can be used to create a new list by applying the provided function to each member of a list and returning those for which the function returns a true value.

*Note: Without values, this function is not executed for array elements. * This function takes a function as an input and/or returns a function. All it does is to apply the provided function to the current item in an array and return the new item.

All functions that take an item from the array as an input and return a new item are said to commute with another function that returns a previous item from an array.

In JavaScript, the if statement can be used to execute a block of code if an event happens at a particular point of a program. The first argument to the if statement is a function followed by an event (in this case, the current click event) and the second argument is the block of code to execute if the event occurs. The if statement following the if is purely syntactic: it simply passes the event to the function it sees matching the conditions.

3. Reduce()

The reduce method applies a function against an accumulator and each element in the array (from left-to-right) has to reduce it to a single value.

Reduce is one of those functions that make you feel lost at first. It takes a function as an input, and it produces a new function as output followed by the input function.

Syntax:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

We use reduce function when a number of arrays need to add them all:

const euros = [29.76, 41.85, 46.5];

const sum = euros.reduce((total, amount) => total + amount);

sum // 118.11

How could we do it differently?

Each element of the array could be an object that sets all the values of a property. That could be the property array.the length itself, or the length property or property whose values are array elements themselves.

  1. forEach()

Lastly, we have forEach() which comes from both Array and Object (and every object that inherits from Object)

This method iterates over an array, executing a provided function for each member of the array. The function you provide will be called once for each element in the array, with that element passed as the first argument.

Syntax:

array.forEach(function(currentValue, index, arr), thisValue)

Example:

var vegetables = ["brinjal", "potato", "tomato"]; fruits.forEach(myFunction);

function myFunction(item, index) { document.getElementById("demo").innerHTML += index + ":" + item + "
"; }

Output:

0:brinjal 1:potato 2:tomato

*Note: Without values, this function is not executed for array elements.

The following two lines are equivalent.

The following function takes any number of arguments and returns the first n such arguments that satisfy a given condition. It returns the first such value in ascending order (i.e. the first argument after removing all the zeros).

This function doesn’t do anything except returning a new object - stringified (aka mapped) by applying the given function to each key in the object. The result of this function is then published to a string which is then used as the key for a new Map object.

Conclusion:

A higher-order function is a very powerful programming concept and one that every JavaScript developer should be familiar with.

I hope you will find this article helpful, try to learn new things, and keep practicing, there is no other way in programming.