In this article, we will see how to use the various type of loops available in JavaScript with arrays. In this article, we will see the implementation of forEach(), for..of, and for loops.
We can use loop through an array in Javascript in the following ways:
- Using the forEach() method
- Using the for…of statement
- Using the basic for loop
- Using While Loop
Method 1: Using the forEach() method
The forEach() method is used to execute code for each element in the array by looping through each of them.
Syntax:
array.forEach( arrayElement => {
// Lines of code to execute
});
Example: In this example, we will loop through an array using the forEach() method and print the values.
Javascript
function loopArray() { let arr = [ 'Item 1' , 'Item 2' , 'Item 3' , 'Item 4' , 'Item 5' ]; arr.forEach(element => { console.log(element); }); } loopArray(); |
Item 1 Item 2 Item 3 Item 4 Item 5
Method 2: Using the for…of statement
The for…of statement can be used to loop through iterable objects and perform the required functions. Iterable objects include arrays, strings, and other array-like objects.
Syntax:
for (arrayElement of array) {
// Lines of code to execute
}
Example: In this example, we will loop through an array using the for..of statement and print the values.
Javascript
function loopArray() { let arr = [ 'Item 1' , 'Item 2' , 'Item 3' , 'Item 4' , 'Item 5' ]; for (element of arr) { console.log(element); } } loopArray(); |
Item 1 Item 2 Item 3 Item 4 Item 5
Method 3: Using the basic for loop
The default for loop can be used to iterate through the array and each element can be accessed by its respective index.
Syntax:
for (i = 0; i < list.length; i++) {
// Lines of code to execute
}
Example: In this example, we will loop through an array using the for loop and print the values.
Javascript
function loopArray() { let arr = [ 'Item 1' , 'Item 2' , 'Item 3' , 'Item 4' , 'Item 5' ]; for (i = 0; i < arr.length; i++) { console.log(arr[i]); } } loopArray(); |
Item 1 Item 2 Item 3 Item 4 Item 5
Method 4: Using While Loop
A While Loop in JavaScript is a control flow statement that allows the code to be executed repeatedly based on the given boolean condition. The while loop is used to iterate over the array.
Example:
Javascript
function loopArray() { let arr = [ 'Item 1' , 'Item 2' , 'Item 3' , 'Item 4' , 'Item 5' ]; let length = arr.length; while (length > 0) { console.log(arr[arr.length - length]); length--; } } loopArray(); |
Item 1 Item 2 Item 3 Item 4 Item 5