3 ways to loop an array in JavaScript | Quick ways

📋 Table Of Content
In this article we will learn about 3 quick ways to loop through an array in JavaScript.
JavaScript loops are use to run a block of code repeatedly until a certain condition is met. It is also use to iterate through items in an array.
In JavaScript there are three easy ways to loop over an array: forEach
loop, for of
loop and simple for
loop.
Lets us see with examples different types of JavaScript loop
forEach() loop in an array in javascript
The forEach()
 method performs a provided function once for each elements in an array.
Let see how to forEach()
loop over an array in JavaScript with an example.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.forEach(element => console.log(element))
// OUTPUT
// Banana
// Orange
// Apple
// Mango
Here we are looping through each element in fruits array using forEach() and element
is the current element in the array that has being processed.
for ..of loop in an array in JavaScript
The for ..of
statement performs a loop iteration over iterable objects like String, Array, or array-like objects.
const array1 = ['a', 'b', 'c'];
for (const element of array1) {
console.log(element);
}
// expected output: "a"
// expected output: "b"
// expected output: "c"
for loop in JavaScript
The for loop
is the most used way of looping through an array in JavaScript before foreach and for of were introduced in ES5 and ES6.
Syntax:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Here:
statement 1
: Is executed only one time before execution of the code block.
statement 2
: It define the condition of the loop for the execution of the code block.
statement 3
: It is executed at the end, after the code block is executed.
Example:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i])
}
//OUTPUT
// Banana
// Orange
// Apple
// Mango
Here the statement 2 (i < fruits.length
) is the condition and the loop will run till it becomes equal to array length. Once the condition is met, the loop stops.
Well, these are the three easy and quick ways to loop through an array in JavaScript.
Related Topics:
How to convert an array of objects to an object in JavaScript ?
How to convert an array to object in javascript?