There is a general requirement when developing in javascript that is to loop through an array. This article will discuss how to iterate through an array in javascript using six different methods and example illustrations.

Table of Contents:-

Loop through array in javascript using for loop

Example:-

Print each element of the array [‘Java’, ‘is’, ‘a’, ‘popular’, ‘language’]

Function:-

let stringArray = ['Java', 'is', 'a', 'popular', 'language'];
for (let i = 0; i < stringArray.length; i++) {
  console.log(stringArray[i]);
}

Output:-

Java
is
a
popular
language

Loop through array in javascript using for each loop

Example:-

Print each element of the array [‘Java’, ‘is’, ‘a’, ‘popular’, ‘language’]

Function:-

let stringArray = ['Java', 'is', 'a', 'popular', 'language'];
stringArray.forEach((eachElement) => {
    console.log(eachElement);
  });

Output:-

Java
is
a
popular
language

Loop through array in javascript using for of

Example:-

Print each element of the array [‘Java’, ‘is’, ‘a’, ‘popular’, ‘language’]

Function:-

let stringArray = ['Java', 'is', 'a', 'popular', 'language'];
for (let forElement of stringArray) {
    console.log(forElement);
  }

Output:-

Java
is
a
popular
language

Loop through array in javascript using for in

Example:-

Print each element of the array [‘Java’, ‘is’, ‘a’, ‘popular’, ‘language’]

Function:-

let stringArray = ['Java', 'is', 'a', 'popular', 'language'];
for(let key in stringArray){
  console.log(stringArray[key]);
}

Output:-

Java
is
a
popular
language

Loop through array in javascript using while loop

Example:-

Print each element of the array [‘Java’, ‘is’, ‘a’, ‘popular’, ‘language’]

Function:-

let stringArray = ['Java', 'is', 'a', 'popular', 'language'];
let length = stringArray.length;
while(length > 0){
  console.log(stringArray[stringArray.length - length]);
  length--;
}

Output:-

Java
is
a
popular
language

Loop through array in javascript using do while loop

Example:-

Print each element of the array [‘Java’, ‘is’, ‘a’, ‘popular’, ‘language’]

Function:-

let stringArray = ['Java', 'is', 'a', 'popular', 'language'];
let length = stringArray.length;
do {
  console.log(stringArray[stringArray.length - length]);
  length--;
}
while (length > 0)

Output:-

Java
is
a
popular
language

Read More:

We hope this article helped you to iterate through an array in javascript. Good Luck !!!