If you’ve been programming for any amount of time, you would be familiar with arrays. They are among the first data structures taught in most programming lectures/courses. For good reason too, because they are pretty easy to work with. But in case you work in JavaScript, using arrays can be made a whole lot simpler with the help of some useful higher-order methods!
The reason that these are called Higher Order Methods is that they can accept/return another function. If this seems a tad bit confusing, then it’s important that you understand why functions are first-class citizens in JavaScript. It is just a fancy way of saying that functions are just like any other type of data, which can be stored, accessed, passed as arguments, and even returned from another method!
The following image does a pretty good job at describing what a higher-order function is
A quick heads up. These higher-order methods will require the usage of callbacks and they will be a lot easier to write if you are familiar with the arrow syntax of ES6. In case you’re not, you can go through the following section to see what it is. Here’s a pretty basic example:
// normal function definition
function add(a, b) {
return (a + b)
}
// arrow syntax
const add = (a, b) => (a + b);
You can convert a normal function definition into its arrow syntax counterpart, using the following steps:
function
keyword and replace it with either const
or let
or var
. We can do this because functions are first-class objects in JavaScript. (Note: In case you want an anonymous function, just remove the function
keyword and move to step 2)=>
in front of the arguments’ list, to indicate that the code following it will be the body of the function.return
keyword, and just type out the expression that needs to be returned!=>
symbol.const alertMsg = () => alert("This is just an example!")
const squared = x => (x ** 2)
Now that you have brushed up on the arrow syntax, let’s begin to understand some higher-order array methods!
for loop
. It invokes a function on **each **array element, and its syntax goes like this:array.forEach((element, index) => {
// some operations on the element
// maybe you want to use the index of the element
});
In case you want to see a pretty contrived example, take a look at the following example.
Example for forEach()
const returnedArr = array.map(currentEle => {
// some operation on currentEle
})
It’s slightly different to the forEach() method, but you should be able to use them interchangeably for most applications. In case you want to know about the differences, you can go through the following article.
The Differences Between forEach() and map() that Every Developer Should Know
#javascript #beginners-guide #es6 #array-methods #programming