Loop Through All Items in an Array in JavaScript
Looping through an array is a foundational skill in JavaScript. Whether you're printing fruit names to the console or processing data items from a server, looping is the key that unlocks the full potential of arrays. The beautiful thing about JavaScript is that it offers a variety of ways to perform this simple—but essential—task.
In this tutorial, we’ll walk through four common and beginner-friendly methods to loop through all items in an array. Each method has its own personality and use case, and we’ll give you a complete example to run and learn from.
Method 1: Using a Classic for
Loop
The traditional for
loop is a reliable and widely used way to iterate through an array using index positions. It gives you full control over the loop’s behavior, and it's great for beginners to understand how array indices work.
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
apple
banana
cherry
Method 2: Using the for...of
Loop
The for...of
loop is a cleaner, more modern way to iterate through arrays in JavaScript. It directly gives you the value of each element, so there’s no need to deal with array indices unless you really want them.
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
apple
banana
cherry
Method 3: Using the forEach()
Method
The forEach()
method is a built-in function on array objects that lets you execute a function for each element in the array. It’s more functional and expressive and often used in production code for its readability.
const fruits = ["apple", "banana", "cherry"];
fruits.forEach(function(fruit) {
console.log(fruit);
});
apple
banana
cherry
Method 4: Using the map()
Method
While map()
is primarily used to transform array elements into a new array, it can also be used to loop through items when a return value is needed. Just be cautious—if you don’t return anything, you'll end up with an array of undefined
values.
const fruits = ["apple", "banana", "cherry"];
const result = fruits.map(fruit => {
console.log(fruit);
return "Fruit: " + fruit;
});
console.log(result);
apple
banana
cherry
[ 'Fruit: apple', 'Fruit: banana', 'Fruit: cherry' ]
When Should You Use Each Method?
If you're learning the ropes, the classic for loop is a great place to start—it teaches you how arrays are structured. As you get more comfortable, you’ll probably gravitate toward for...of for simplicity, or forEach when writing clean functional code. Use map() only when you're transforming data and returning a new array.
Comments
Loading comments...