Loop through an array in JavaScript

Looping through an array in JavaScript is a common task that you will encounter when working with arrays. There are several ways to loop through an array in JavaScript, but two of the most common methods are using a for loop or a forEach loop.

Using a for loop:

javascript
let arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}

In this example, we define an array arr with five elements. We then use a for loop to iterate through each element in the array, starting at the first index (i = 0) and continuing until the last index (i < arr.length). The loop body simply logs each element to the console.

Using a forEach loop:

javascript
let arr = [1, 2, 3, 4, 5];
arr.forEach(function(element) {
console.log(element);
});

In this example, we use the forEach method of the array object to loop through each element in the array. The forEach method takes a callback function that is called for each element in the array. The element parameter of the callback function represents the current element being iterated over.

Both of these methods will produce the same output:

1
2
3
4
5

You can choose the method that best fits your needs and coding style.