Loop over an array in JavaScript

To loop over an array in JavaScript, you can use one of several loop constructs, including the for loop, the for…of loop, and the forEach() method.

Here’s an example of using a for loop to loop over an array of numbers:

javascript
const numbers = [1, 2, 3, 4, 5];

for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}

This will output each number in the array on a new line:

1
2
3
4
5

Here’s an example of using a for…of loop to loop over the same array:

javascript
const numbers = [1, 2, 3, 4, 5];

for (const number of numbers) {
console.log(number);
}

This will output each number in the array on a new line, just like the previous example.

Finally, here’s an example of using the forEach() method to loop over the same array:

javascript
const numbers = [1, 2, 3, 4, 5];

numbers.forEach(function(number) {
console.log(number);
});

This will also output each number in the array on a new line.

All three of these approaches accomplish the same thing, but they differ in syntax and may be better suited to different situations. Choose the approach that makes the most sense for your specific use case.