A Beginner’s Guide to JavaScript Array Loop
Difference between forEach(),filter() and map() methods
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.
const array_name=[item1,item2,item3,item4]
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.
let entrance = ['James',79,true]
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
let fruits =['mango','oranges','grapes','banana']
An array is accessed by the array name and the items in the array can be accessed with the index of the array.
console.log(fruits)
//[0] mango
//[1]oranges
//[2]grapes
//[3]banana
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
.
console.log(fruits[0])
//mango
console.log(fruits[1])
//oranges
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]
.
console.log(fruits.length)
//4
console.log(fruits[fruits.length-1])
//bananas
An index that does not exist in an array returns undefined
console.log(fruits[4])
//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()
array_name.forEach(function,thisArg)
map()
array_name.map(function,thisArg)
filter()
array_name.filter(function,thisArg)
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.
array_name.forEach((element,index,array)=> //code to be executed )array_name.map((element,index,array)=> //code to be executed )array_name.filter((element,index,array)=> //code to be executed )
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
.
let numbers=[45,34,78,21,14,94]
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:
numbers=numbers.forEach((element)=>(element*2))
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
console.log(numbers)//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:
numbers=numbers.forEach((element)=>console.log(element*2))
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.
//90
//68
//156
//42
//28
//188
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
let newNumbers=[]numbers.forEach((element)=>newNumbers.push(element*2))console.log(newNumbers)
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
let sumNumbers=0numbers.forEach((element,index,array)=>sumNumbers+=element)console.log(sumNumbers)
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)
.
//286
Let’s consider another case use of forEach()
in the product of the numbers
let productNumbers=1numbers.forEach((element)=>productNumbers*=element)console.log(productNumbers)
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.
//3298080240
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
numbers=numbers.map((element,index)=>element*index)console.log(numbers)
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)
//[0, 34, 156, 63, 56, 470]
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.
let indexNumbers=numbers.map((element,index)=>element*index)console.log(indexNumbers)
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.
//[0, 34, 156, 63, 56, 470]
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.
let oddNumbers=numbers.filter((element)=>element%2!=0)console.log(oddNumbers)
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.
//[45, 21]
Let’s consider another case for a statement that do not exist within the array.
let thousandNumbers=numbers.filter((element)=>element >999)console.log(thousandNumbers)
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.