How to Loop through an Array in JavaScript



How to Loop through an Array in JavaScript | ninjasquad

In this tutorial, we’ll learn how to loop through elements of an Array using different ways in JavaScript.

for loop

The for is used to loop through an the index of an Array

const array = ["one", "two", "three"];

for(var i=0; i<array.length; i++){
  console.log(i, array[i]);
}

Output

0 "one" 1 "two" 2 "three"

for-in loop

The for-in statement loops through the index of an Array.

const array = ["one", "two", "three"];
for (const index in array){
    console.log(index, array[index]);
}

Output

0 "one" 1 "two" 2 "three"

for-of loop

The for-of statement loops through the values of an Array.

const array = ["one", "two", "three"];
for (const element of array){
    console.log(element);
}

Output

one two three

Array.forEach()

The Array.forEach() method takes a callback function to loop through an Array. We can use ES6 arrow functions in callback.

const array = ["one", "two", "three"];

array.forEach((item, index) => console.log(index, item));

Output

0 "one" 1 "two" 2 "three"

That’s it! These are the four different ways to loop-through an Array in JavaScript. It is recommended to use Array.forEach() with arrow function which makes your code very short and easy to understand.

Though there is a limitation that we can not use break; and continue; flow control statements with Array.forEach() method. If you want to do so, use for, for-in or for-of loop instead.



Source: Internet

Leave a Comment

We are offering free coding tuts

X