By the end of this lesson, learners will:
for
, while
, and for...of
loops with arraysAn array is a list-like data structure used to store multiple values in one variable.
Example:
let fruits = ["apple", "banana", "cherry"];
If you want to:
…you’ll need to loop through the array.
for
Loop with Arraysfor (let i = 0; i < array.length; i++) {
// use array[i]
}
let fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Output:
apple
banana
cherry
✅ i
starts at 0 (first index)
✅ fruits[i]
gets each item
✅ fruits.length
is the total number of items
while
Loop with ArraysYou can also loop through arrays with a while
loop.
let colors = ["red", "green", "blue"];
let i = 0;
while (i < colors.length) {
console.log(colors[i]);
i++;
}
Same output:
red
green
blue
for...of
Loop (Newer & Cleaner)for...of
is a modern and beginner-friendly way to loop through array values directly — no index needed.
for (let item of array) {
// use item directly
}
let animals = ["cat", "dog", "elephant"];
for (let animal of animals) {
console.log(animal);
}
Output:
cat
dog
elephant
✅ Simpler to read
✅ No need to manage index manually
✅ Great for most use cases
let products = ["Laptop", "Phone", "Tablet"];
for (let product of products) {
console.log("Product: " + product);
}
Output:
Product: Laptop
Product: Phone
Product: Tablet
for...of
)The for...of
loop doesn’t give you the index directly, but you can combine with .entries()
:
let books = ["Book A", "Book B"];
for (let [index, book] of books.entries()) {
console.log(index + ": " + book);
}
Output:
0: Book A
1: Book B
<=
instead of <
:// BAD: includes undefined!
for (let i = 0; i <= fruits.length; i++) {
console.log(fruits[i]); // last item is undefined!
}
✅ Always use < fruits.length
to stay within bounds.
for (let i = 0; i < fruits.length; i++) {
console.log(i); // prints 0, 1, 2 (the index)
console.log(fruits[i]); // prints the fruit (correct!)
}