Four ways to visit every item
All four visit both items in order. The last line shows that forEach returns undefined.
You can walk through an array with a classic for loop, for...of, forEach or map; forEach runs a function for each item and returns nothing, can't be stopped early, and is the wrong choice when you need break, a result array, or await.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Print each name in ["Asha", "Ravi", "Meera"] as 1. Asha, 2. Ravi, 3. Meera using for...of and entries().
Loop over [3, 7, -2, 9] and stop at the first negative number, printing Negative at index 2.
Explain it without notes
What is the difference between forEach and map?
How do you stop looping through an array early?
Why shouldn't you use forEach with async callbacks when order or completion matters?
Why is for...in a poor choice for arrays?
Console
(nothing was printed)Expected console output
for 0 red
for 1 green
for...of red
for...of green
entries 0 red
entries 1 green
forEach 0 red
forEach 1 green
undefined