Loop through an array in JavaScript
An array is a variable used to store an ordered list of value which can be of different datatypes. Arrays can store strings, numbers, booleans, objects and even other arrays. The ordered nature of arrays make them so that each value is specified by its own index. JavaScript arrays are zero-indexed.
Values in an array are stored in a list format, to access the values stored in the array the need for loops arise.
JavaScript loops
Looping can can be described as a way of moving from one element to another in an array without changing the positions of the elements. A JavaScript loop is a program that carries out tasks repeatedly based on a condition passed to it. With loops values of an array can be accessed individually and specified operations performed on them. There are several ways to loop through an array in JavaScript. Below we’ll discuss a few JavaScript loops and how they work.
JavaScript while loop
The JavaScript while
loop runs a statement as long as the specified condition remains true.
while(condition) {
//statement to be executed
}
const nums = [11, 22, 33, 44];
let x = 0;
while (x < nums.length) {
console.log(nums[x]);
x++;
}
//the above code will print
//11
//22
//33
//44
Javascript do…while loop
The do...while
loop is similar to the while loop, except that it runs the statement before it checks the condition. This process is repeated until the condition turns false and the loop is terminated. This means the statement is executed at least once.
do { //statement to be executed
} while (condition)
let sum;
let x = 0;
do {
x += 1;
sum = x;
} while (sum < 4);
console.log(sum);
//the above code would print
//4
JavaScript for loop
The JavaScript for
loop, similar to the other types of loops in functionality executes a program until a certain condition is met. The for
loop consists of three subjective expressions which are separated by semicolons all wrapped in parenthesis before the statement block of code.
for (initializer ; condition ; iterator) {
//statement to be executed
}
The initializer sets the initial value of the expression to be evaluated.
The condition is mostly a boolean expression that determines if the loop should continue or stop.
The iterator is a counter that works to update the initial value till the condition is met.
for (let x = 0; x < 4; x++) { console.log(x); } // The code above would print //0 //1 //2 //3
Javascript for… of loop
The for… of
loop loops through each value of an array sequentially and performs the operation specified on the statement on each value of the array.
for (newVariable of array) {
//statement to be executed
}
Here newVariable
is the current value being processed in the array. Also, newVariable
can be declared with let
, const
or var
.
const nums = [10, 20, 30, 40];
for (let num of nums) {
num /= 2;
console.log(num);
}
//The above code would print
//5
//10
//15
//20
JavaScript for...in loop
The JavaScript for… in
loop allows programmers to iterate(loop) over key property of an object.
It's widely accepted that it is better to use the for… of loop over the for.. In loop when looping an array.
for (variable in object){
//statement to be executed
}
const names = {
firstName: "Esther",
lastName: "Schmedtman",
};
let fullName = "";
for (const name in names) {
fullName += names[name] + " ";
}
console.log(fullName);
//The expected result is : 'Esther Schmedtman'
Javascript forEach loop
The forEach()
is a JavaScript method that loops through an array and executes a user defined callback function on each element of the array.
forEach (function (curr, i, arr) {
//statement to be executed
})
The provided callback function comes with three parameters.
curr
is the current value being processed.i
indicates the index of the value being processed within the array.arr
is the array itself.const arr = ["john", "jane", "doe"]; arr.forEach(function (curr, i, arr) { console.log(curr); }); //The above code would print //john //jane //doe
JavaScript map
map()
is a built in javascript method for iterating through an array. It returns( outputs) a new array with the results of calling a function on each array element it comes across. The callback funtion that accompanies the map method has access to the same parameters as the forEach()
method.
map (function (curr, i, arr) {
//statement to be executed
})
const arr = [1, 2, 7, 8];
const mappedArr = arr.map(function (curr, i, arr) {
return curr + 1;
});
console.log(mappedArr);
//The expected output is : [2, 3, 8, 9]
Javascript filter
The filter()
method returns a new array from an existing array where the elements in the new array must pass a certain test from the callback function in the existing array. If no element from the existing array passes the test, filter()
returns an empty array. Also, filter has access to the same parameters the forEach()
callback function does.
filter (function (curr, i, arr) {
//statement to be executed
})
const nums = [70, 8, 1, 2, 3, 19, 40];
const filteredArr = nums.filter(function (curr, i, arr) {
return curr > 10;
});
console.log(filteredArr);
//The expected output is : [70, 19, 40]
Javascript reduce
The reduce()
method executes a subjective "reducer " callback function on each element of the array sequentially passing the resulting value from one calculation to the next.
reduce()
has access to the same parameters as forEach()
plus an additional ''previous value'' parameter. The reduce()
method returns a single value.
reduce(function(previousValue, curr, i, arr){
//statement to be executed
})
const reduceArr = [1, 2, 3, 4];
const reducedValue = reduceArr.reduce(function (previousValue, currentElement) {
return previousValue + currentElement;
});
console.log(reducedValue);
//The expected result is : 10
Wrapping up
An underscore _
can be used in place of function parameters that wont be used.
//for example
const myArr = ["michael", "jackson", "jude"];
myArr.forEach(function (_, i, arr) {
console.log(i);
});
//The expected output is : 0, 1, 2
In this article, we discussed different methods of looping an array. It is important that you understand all of these methods and the right conditions to use them that will make your code cleaner and DRY (Don't repeat yourself).
Subscribe to my newsletter
Read articles from Velia Precious directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Velia Precious
Velia Precious
Web Developer and Technical Writer