How to loop through an array in JavaScript

How to loop through an array in JavaScript

In this tutorial, we are going to learn about different ways to loop through an array in JavaScript.

For loop

for loop helps us to loop through an array and access the elements inside an array.


const arr = [1,2,3,4];

for (let i=0;i<arr.length;i=i+1){

// first iteration  1
//second iteration 2
//third iteration 3
//fourth iteration 4

For in loop

for in loop gives us indexes of the array by using that indexes we can access the array elements.


for (let index in arr){

For of loop

for..of loop directly gives us elements of the array instead of indexes.


for(let element of arr){

forEach method

By using forEach() method, we can also access the array elements directly.


The forEach method runs the provided callback function once on each element present in the array.

While loop

let index= 0; //initialized with 0

while(index < arr.length){
  console.log(arr[index]); //logging element
  index = index+1; //incrementing the index