A Beginner’s Guide to JavaScript Array Loop

Difference between forEach(),filter() and map() methods

Onoigboriaose
Nur: The She Code Africa Blog
7 min readSep 5, 2022

--

Arrays are a very important part of programming as it helps to have more organized codes which are easier to maintain. JavaScript has several looping methods and It is quite a task to choose which array looping method best solves a problem. A better and simplified understanding of arrays and its methods will help to identify which is needed per time to solve a problem.

Other than the basic for while and while ..do loops in JavaScript, there are some special methods tied to arrays that make array iteration more interesting. These are the forEach(),filter()and map() array methods. These methods are similar to iteration methods in JavaScript and in this article, we will explain these method in details and consider some simple use cases.

I hope this article, can help as a guide for understanding arrays and looping through arrays using forEach(),filter() and map() . Feel free to run the examples in this article your code editor.

Introduction to Arrays

Arrays are special objects with an ordered collection of data stored in a single variable. They are very useful in storing similar data or data from common source.

The syntax above uses the array literals to create JavaScript arrays with array_name as the name of the array and item1,item2… as the elements in the array. The square bracket[] is used to enclose the elements in the array and each item is separated with , .

An array in JavaScript can contain mixture of data types such as String, Boolean, Numbers and objects. A simple illustration is in entrance below.

The interesting thing about arrays is that irrespective of the data types it contains, the array methods remain the same and the data types have the same properties as a singular variables. Another example, is a variable containing elements of same data types fruits

An array is accessed by the array name and the items in the array can be accessed with the index of the array.

To access individual items in an array, the square bracket is used to hold the index which is placed in front of the array_name .The first item of an array has an index of 0.

The length property of an array is the number of elements in an array which begins counting from 1 unlike the indexing, and the last element of an array can easily be accessed array_name[array_name.length-1].

An index that does not exist in an array returns undefined

With the understanding that arrays contains an ordered list of elements, it may be required to execute a particular task over each item and this is know as a loop.

A loop is a program that executes a particular function over a predetermined number of times. In an array, this predetermined time can simply be the length of the array, such that every element on the array is acted upon once by the function. Let’s consider the following array iteration methods:

forEach()

map()

filter()

The above code snips are forEach(),map() and filter()syntax respectively. The three methods all have the same syntax as the . notation is used to join the method to the array_name and each of the method takes in two parameter a callback function and thisArg but the functions are executed differently which will be considered as we go further. The callback function can either be an arrow function, an inline function expression or a callback function written somewhere else in the .js file.The possible arguments to the function are element, index and array . Only the element is a required argument, the other two are optional. The thisArg is an optional parameter, it is used by the callback function when assigned but most of the time it is .For easy reference,we will use arrow function through these methods.

  • element: current element value in the array.
  • index: current index in array.
  • array: entire array.

Let’s consider some simple use cases of these methods using the array numbers .

forEach() in use

The forEach() method can be used to loop over an array to returns an ordered list refined by the function. The forEach() method when used with return prints undefined. Let’s see this with an example:

Remember that the => function has an implicit return so, you do not need to add return keyword in the function. When this is printed to the console it returns undefined

And why is this so? The forEach() method is to access elements inside an array and it does not accept a return keyword but this can be overwritten by invoking another function into the callback . Let’s examine a simple use case in which the return is over written:

Here, console.log() overrides the return keyword and forEach() method loops over numbers array and executes the function element*2 on each element in the array and prints (element*2) as the output to the console instead of a return. Note that it does not return a new array but an ordered list of the numbers array.

In other for forEach()iteration to return a new array, the function is mutated by using another array method called push(). Let’s consider an example

The array newNumbers is declared empty, and push() is used to populate the empty array from the callback function in forEach(). For every instance the foreach() runs, it grabs the element and performs newNumbers.push(element*2). Just like the console.log, the push() overrides the return and outputs into the newNumbers array without changing the order of the elements. When newNumbers is logged to the console, it prints an array

//[90, 68, 156, 42, 28, 188]

The forEach() method can also return a single value such as the sum or product of all the elements in an array

From the snip above, we declare a variable sumNumbers and assigned it a value 0 . To get the sum of numbers you iterate the array using the forEach()method and for each instance the loop runs, beginning from numbers[0],the value of the array stored in the argument element is added to the variable sumNumbers .The variable sumNumbers, acts as the incremental variable to store the value for each iteration and output the sum of the array at the end of the loop console.log(sumNumbers) .

Let’s consider another case use of forEach() in the product of the numbers

From the snip above, the variable productNumbers is declared and assigned a value 1 . Unlike sumNumbers which was assigned a value 0 ,this is because in arithmetic, the product of 0 and any value returns 0.So,for every instance the forEach() runs ,it simply grabs the element and multiplies it by productNumbers. At the end of the loop, productNumbers is requested as output console.log(productNumbers) which prints the value of the iteration to the console.

Map() in use

The map method returns a new array by executing map(function) once for every element in the initial array. The new array is refined by the callback function. This is an array to array method-it always returns an array

Let’s consider a simple example using numbers arrays

The function called for each element in the array is element*index. For every instance the loop runs , it grabs the element beginning from the index[0] and executes element*index. For us to get the output, notice that the new array is still saved to numbers which is printed then to the console console.log(numbers)

It is also possible to get a new array with a different array_name from the initial array if the initial array is required for a later function.

Since the map() always returns an array irrespective of its use case, the new array is created by declaring a variable indexNumbers and assigning numbers.map((element,index)=>element*index) its value. Printing indexNumber to the console, we get the output indexNumber in an array.

filter() in use

This is perhaps the easiest to recall method because as the name implies, it simply filters the array based on the condition specified in the callback function. How does filter() work? This might be lingering on your mind don’t worry, let’s consider an example to bring clarity.

Just like map() that always returns an array, a variable oddNumbers is declared to store the array returned from the filter () method. The callback function executes a code that determines the element that makes up the new array. For every instance of the loop just like the forEach ()and map()it simply grabs the element but in this case, the callback function acts as a conditional to check if the function returns true for each element in the array. The new array is populated by only the elements that are true to the statement. Based on the conditions in the above snip, element%2!=0 returns only the odd numbers from the array. Printing oddNumbers to the console, we have only the odd numbers from the numbers array.

Let’s consider another case for a statement that do not exist within the array.

The condition for this callback function is to return an array consisting of numbers >999 .Looking at the array numbers ,all element meets the condition elements<999 and none is true element>999.In this case, the output from the console when thousandNumbers is called is an empty array

Conclusion

Good to know you read this far! In this article, we introduced array briefly and dived into array loops considering some basic use cases of forEach(),map() and filter() methods.

I hope this article could help you set the ball rolling to jump into arrays and array loops in practice. Always remember that both map() and filter() will always return arrays.

For contribution, comments or more clarity, feel free to leave a comment below or send a direct message to me via LinkedIn.

--

--