How to use loop through an array in JavaScript?
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:
<!DOCTYPE html><html> <head> <title> How to use loop through an array in JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to use loop through an array in JavaScript? </b> <p> Looping through the array: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'] </p> <p>Output: <div class="output"></div></p> <button onclick="loopArray()"> Click to check </button> <script type="text/javascript"> function loopArray() { list = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5']; list.forEach(element => { document.querySelector('.output').innerHTML += '<li>' + element + '</li>'; }); } </script></body> </html> |
Output:
- Before clicking the button:

- After clicking the button:

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:
<!DOCTYPE html><html> <head> <title> How to use loop through an array in JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to use loop through an array in JavaScript? </b> <p> Looping through the array: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'] </p> <p>Output: <div class="output"></div></p> <button onclick="loopArray()"> Click to check </button> <script type="text/javascript"> function loopArray() { list = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5']; for (element of list) { document.querySelector('.output').innerHTML += '<li>' + element + '</li>'; } } </script></body> </html> |
Output:
- Before clicking the button:

- After clicking the button:

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:
<!DOCTYPE html><html> <head> <title> How to use loop through an array in JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to use loop through an array in JavaScript? </b> <p> Looping through the array: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'] </p> <p>Output: <div class="output"></div></p> <button onclick="loopArray()"> Click to check </button> <script type="text/javascript"> function loopArray() { list = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5']; for (i = 0; i < list.length; i++) { document.querySelector('.output').innerHTML += '<li>' + element + '</li>'; } } </script></body> </html> |
Output:
- Before clicking the button:

- After clicking the button:




.png)