JavaScript provides several ways to loop through an array, each with its own set of advantages and disadvantages. In this article, we will explore the most common methods for iterating over an array in JavaScript.
For loop
One of the most basic and widely used ways to loop through an array is using a for
loop. The for
loop allows you to specify the starting and ending points of the loop, as well as the increment or decrement value. Here is an example of using a for
loop to iterate over an array:
let myArray = [1, 2, 3, 4, 5];
for (let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
In this example, the for
loop starts at the index of 0 and ends at the index of myArray.length - 1
. The variable i
is incremented by 1 on each iteration of the loop, allowing us to access each element of the array one at a time.
For-of loop
ES6 introduced a new feature called the for-of
loop, which is specifically designed for iterating over arrays and other iterable objects. The for-of
loop provides a more concise and easy-to-read syntax for looping through an array. Here is an example of using a for-of
loop:
let myArray = [1, 2, 3, 4, 5];
for (let element of myArray) {
console.log(element);
}
In this example, the for-of
loop iterates over each element of the array, assigning the current element to the variable element
on each iteration.
ForEach() method
JavaScript arrays also have a built-in method called forEach()
that can be used to loop through an array. The forEach()
method takes a callback function as its parameter, which is called for each element of the array. Here is an example of using the forEach()
method:
let myArray = [1, 2, 3, 4, 5];
myArray.forEach(function(element) {
console.log(element);
});
In this example, the forEach()
method calls the provided callback function for each element of the array, passing in the current element as a parameter.