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
- Loop through an array using forEach
- Loop through an array using for of
- Loop through an array using for in
- Loop through an array using while
- Loop through an array using do while
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:-
Frequently Asked:
- Javascript: Check if two arrays are equal
- Javascript: Get loop counter/ index in loop
- Get a Subset of Javascript’s Object Properties (4 ways)
- Javascript: Sort an Array of Objects by Property Value
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:
- Javascript: Insert an item to array at specific index
- Javascript: Check if an array is empty
- Javascript: Convert array to string (4 ways)
I hope this article helped you to loop through an array in javascript. Good Luck !!!