Early exit: for...of can stop, forEach can't
return inside forEach only ended that one call; all 6 items were still visited. find stops by itself.
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...of found 15 after 3
forEach visited 6
find: 15