JavaScript Array Iteration (Live Playground)
Iterating over arrays is a common operation in programming, allowing you to perform tasks for each element in the array. In this tutorial, we will discuss various techniques for iterating over arrays in JavaScript, including using for loops, for...of loops, and the forEach method.
Using for Loop
A for loop is a traditional way of iterating over arrays. You can use the loop counter as the index to access array elements.
Example:
const fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// Output:
// apple
// banana
// cherry
Using for...of Loop
The for...of loop is a more modern and concise way of iterating over arrays. It directly gives you access to each element in the array.
Example:
const animals = ['dog', 'cat', 'elephant'];
for (const animal of animals) {
console.log(animal);
}
// Output:
// dog
// cat
// elephant
Using forEach Method
The forEach method is another convenient way of iterating over arrays. It executes a provided function for each element in the array.
Example:
const colors = ['red', 'green', 'blue'];
colors.forEach((color, index) => {
console.log(`Color ${index + 1}: ${color}`);
});
// Output:
// Color 1: red
// Color 2: green
// Color 3: blue
Conclusion
Understanding various techniques for iterating over arrays in JavaScript is essential for processing array data. By mastering the for loop, for...of loop, and forEach method, you can handle array iteration tasks more efficiently in your programs.