Learn how to iterate through arrays using different types of loops to access and manipulate each item. This is essential for working with lists of data in real applications.
When you have a list of items (e.g., usernames, scores, tasks), you often need to:
Rather than repeating the same code manually, you can use loops to automate this process.
for
LoopThe classic, most flexible loop:
let fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
i
is the indexfruits[i]
accesses each valuefruits.length
keeps the loop within boundsfor...of
LoopA simpler way to loop through the values in an array:
for (let fruit of fruits) {
console.log(fruit);
}
forEach()
MethodAn array method that takes a callback function and runs it once for each element:
fruits.forEach(function(fruit) {
console.log(fruit);
});
Or with arrow function:
fruits.forEach(fruit => console.log(fruit));
let users = ["Anna", "Ben", "Charlie"];
// Using for loop
for (let i = 0; i < users.length; i++) {
console.log(i + ": " + users[i]);
}
// Using for...of loop
for (let user of users) {
console.log("Hello, " + user + "!");
}
let shoppingList = ["milk", "bread", "eggs"];
shoppingList.forEach(item => {
console.log("You need to buy: " + item);
});
i <= array.length
will go out of boundsforEach()
does not support break
or continue