You have used for loops with indexes. JavaScript also offers for...of, forEach, entries() and keys(). Which loop should you reach for, and why?
Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.
02Start with working code
for...of gives values; entries() gives index and value pairs.
const fruits = ["apple", "pear", "plum"];
for (const fruit of fruits) console.log(fruit);
for (const [i, fruit] of fruits.entries()) console.log(i, fruit);
03Objective and prerequisites
Learning objective: Iterate arrays with for, for...of, entries() and forEach, choose the right loop for the task, and iterate strings and arrays of objects.
Skills practised: Arrays, Iterating over collections.
04Explanation
for (const item of list) visits every element in order. It is the clearest loop when you need each value.
When you also need the position, use for (const [i, item] of list.entries()) or a classic for (let i = 0; i < list.length; i++).
list.forEach((item, i) => { ... }) calls a function for each element. Lesson 31 explores it in depth.
Arrays of objects are the most common data in real applications. Inside the loop, read properties of each object: for (const order of orders) total += order.total;.
for...of uses the iteration protocol, so it also works on strings, Sets, Maps, NodeLists and generators. for...in iterates enumerable property keys (as strings, including inherited ones) and should not be used for arrays.
break, continue and return work in for and for...of, but not inside a forEach callback. Use for...of when the loop may stop early.
Mutating an array while iterating it (push or splice inside the loop) changes which elements are visited. Build a new array, or iterate a copy.
Object.entries(obj) turns an object into [key, value] pairs, so the same for...of pattern iterates object data.
05Definitions
for...of
A loop that visits each value of an iterable such as an array or string.
entries()
Returns [index, value] pairs for an array.
Iterable
A value that for...of can loop over, such as an array, string, Set or Map.
for...in
A loop over an object's property names; not intended for arrays.
Array of objects
A list where each element is an object with the same properties.
ex-029-01Three loops, one result Browser-executable JavaScript
Classic for, for...of and forEach can produce the same output.
const colours = ["red", "green"];
for (let i = 0; i < colours.length; i++) console.log("for:", colours[i]);
for (const c of colours) console.log("of:", c);
colours.forEach((c) => console.log("forEach:", c));
Sample input
None
Expected output
for: red
for: green
of: red
of: green
forEach: red
forEach: green
A dashboard loops over today's orders (an array of objects) to show the count, the paid total and a numbered list of orders that still need attention.
const orders = [{ id: 7, ok: true }, { id: 8, ok: false }];
for (const [i, o] of orders.entries()) {
if (!o.ok) console.log(`${i + 1}. order ${o.id} needs attention`);
}
12Knowledge check
1. What is printed?
let s = "";
for (const x of ["a", "b"]) s += x + " ";
console.log(s.trim());
a b
0 1
undefined
a
2. Which loop should not be used to read array values?
for
for...of
for...in
forEach
3. Where does break NOT work?
for
for...of
while
inside a forEach callback
4. What is printed?
for (const [i, v] of ["a"].entries()) console.log(i, v);
[0, "a"]
0 a
a 0
["a", 0]
5. Why is total NaN?
let total = 0;
for (const item of cart) total += item;
for...of is wrong
It adds the object, not its price
total should start at 1
objects cannot be looped
6. You need each value and might stop early. Which loop?
forEach
for...of
for...in
Both forEach and for...of
13Solutions and tests
Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.
Automated acceptance tests for this lesson
These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.
Values, not keys: Prints Total: 20; Uses for...of
Numbered list: Prints the list; Uses entries()
Low-stock report: Prints the report; low is correct
ex-029-01: output matches the documented expected output
ex-029-02: output matches the documented expected output
ex-029-03: output matches the documented expected output
ex-029-04: output matches the documented expected output
The lesson lives in the companion repository at curriculum/level-02-core-development/module-06-arrays-and-collections/lesson-029-iterating-over-collections/. Every example on this page is generated from those files.
The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.
15Summary and next steps
for...of is the clearest loop for values.
entries() gives index and value.
forEach calls a function per element but cannot break.
Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.
Concept explanationiterating arrays
Context: I am learning iterating arrays in JavaScript.
Task: Compare for, for...of, entries(), forEach and for...in with one shared example and say when each is the right choice.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code predictioniterating arrays drill
Context: I have practised iterating arrays.
Task: Show me six loops and ask what each prints, including one for...in trap.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debuggingiterating arrays bug
Context: My loop adds up to a strange string like 0012 instead of a number.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generationiterating arrays practice
Context: I finished the iterating arrays exercises.
Task: Create three exercises looping over arrays of objects with exact output.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code reviewiterating arrays review
Context: Here is my code that uses iterating arrays.
Task: Review my loops and suggest the clearest loop type for each.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.