Loop through an array in javascript (6 ways)

While working in javascript arrays, we often encounter a need to loop through an array to process each element. This article will see different ways to loop through an array, along with example illustrations.

Table of Contents:

Loop through an array using for loop

Example:-

Loop through the array [“Hello”, “This”, “Is”,”Language”] and print each element on console.

Code:-

let myArray = ["Hello", "This", "Is","Language"];
var length = myArray.length;
 for (var i = 0; i < length; i++)
 {
    console.log(myArray[i]+ ": " + i );
 }

Output:-

Hello: 0
This: 1
Is: 2
Language: 3

Loop through an array using forEach

Example:-

Loop through the array [“Hello”, “This”, “Is”,”Language”] and print each element on console.

Code:-

 let myArray = ["Hello", "This", "Is","Language"];
 myArray.forEach(function (element, index )
 {
  console.log(element + " : ",index);
 });

Output:-

Hello :  0
This :  1
Is :  2
Language :  3

Loop through an array using for of

Example:-

Loop through the array [“Hello”, “This”, “Is”,”Language”] and print each element on console.

Code:-

let myArray = ["Hello", "This", "Is","Language"];
for (const element of myArray)
{
    console.log(element);
}

Output:-

Hello
This
Is
Language

Loop through an array using for in

Example:-

Loop through the array [“Hello”, “This”, “Is”,”Language”] and print each element on console.

Code:-

let myArray = ["Hello", "This", "Is","Language"];
for (var index in myArray)
{
    console.log(myArray[index]);
}

Output:-

Hello
This
Is
Language

Loop through an array using while

Example:-

Loop through the array [“Hello”, “This”, “Is”,”Language”] and print each element on console.

Code:-

let myArray = ["Hello", "This", "Is","Language"];
var index = 0;
while(element = myArray[index++])
{
    console.log(element);
}

Output:-

Hello
This
Is
Language

Loop through an array using do while

Example:-

Loop through the array [“Hello”, “This”, “Is”,”Language”] and print each element on console.

Code:-

let myArray = ["Hello", "This", "Is","Language"];
let index=0;
do 
{
  console.log(myArray[index]);
  index++;
}
while (myArray.length>index);

Output:-

Hello
This
Is
Language

Read More:

I hope this article helped you to loop through an array in javascript. Good Luck !!!

Advertisements

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top