We use iteration to look at each item in a list one by one. This helps us do something with every item, like printing or changing it.
0
0
Iterating over arrays in Javascript
Introduction
You want to print all names in a list to the screen.
You need to add 1 to every number in a list of scores.
You want to find if a list has a certain word.
You want to create a new list with only some items from the original list.
Syntax
Javascript
const array = [item1, item2, item3]; // Using for loop for (let index = 0; index < array.length; index++) { const currentItem = array[index]; // do something with currentItem } // Using for...of loop for (const item of array) { // do something with item } // Using forEach method array.forEach((item, index) => { // do something with item });
The for loop gives you the index and item.
The for...of loop is simpler when you only need the item.
Examples
This prints each fruit using a classic for loop.
Javascript
const fruits = ['apple', 'banana', 'cherry']; for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); }
This prints each fruit using a for...of loop, which is easier to read.
Javascript
const fruits = ['apple', 'banana', 'cherry']; for (const fruit of fruits) { console.log(fruit); }
This prints each fruit with its index using the forEach method.
Javascript
const fruits = ['apple', 'banana', 'cherry']; fruits.forEach((fruit, index) => { console.log(`${index}: ${fruit}`); });
Shows that loops do nothing if the array is empty.
Javascript
const emptyArray = []; for (const item of emptyArray) { console.log(item); } // No output because the array is empty
Sample Program
This program shows three ways to go through an array and print each color with its position.
Javascript
const colors = ['red', 'green', 'blue']; console.log('Colors before iteration:'); console.log(colors); console.log('\nIterating with for loop:'); for (let index = 0; index < colors.length; index++) { console.log(`Color at index ${index} is ${colors[index]}`); } console.log('\nIterating with for...of loop:'); for (const color of colors) { console.log(`Color: ${color}`); } console.log('\nIterating with forEach method:'); colors.forEach((color, index) => { console.log(`Index ${index}: ${color}`); });
OutputSuccess
Important Notes
Time complexity is O(n) because you look at each item once.
Space complexity is O(1) if you only read items, no extra storage.
Common mistake: Changing the array length while looping can cause errors.
Use forEach when you want simple code and don't need to break early.
Use for loop if you need the index or want to stop early with break.
Summary
Iteration lets you do something with every item in an array.
Use for, for...of, or forEach depending on your needs.
Remember to handle empty arrays safely.