JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 6: Arrays and CollectionsLesson 29 of 150About 40 minutes

Lesson 29: Iterating over collections

01Opening question

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.

You need: Lesson 16: For loops, Lesson 28: Searching and sorting arrays

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;.

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.

Open the full glossary

06Visual learning object

Array search explorer. Watch a loop compare each element in turn until it finds a match, and compare the result with includes, indexOf and find.

Loading the interactive object…

Open the full Array search explorer page with its guided experiment.

07Examples

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
Common mistake
Using for...in, which gives "0" and "1".
Try this
Print each colour in capitals with for...of.
Source
examples/ex-029-01-three-loops.js (repository pending publication)

ex-029-02Index and value together Browser-executable JavaScript

entries() with destructuring gives both.

const steps = ["Add to cart", "Checkout", "Pay"];
for (const [i, step] of steps.entries()) {
  console.log(`Step ${i + 1}: ${step}`);
}
Sample input
None
Expected output
Step 1: Add to cart Step 2: Checkout Step 3: Pay
Common mistake
Forgetting that i starts at 0.
Try this
Mark the last step with "(final)".
Source
examples/ex-029-02-entries.js (repository pending publication)

ex-029-03Looping over objects Browser-executable JavaScript

Each element is an object; read its properties.

const orders = [
  { id: 1, total: 20, paid: true },
  { id: 2, total: 35, paid: false },
  { id: 3, total: 15, paid: true }
];
let paidTotal = 0;
for (const order of orders) {
  if (order.paid) paidTotal += order.total;
}
console.log("Paid:", paidTotal);
Sample input
None
Expected output
Paid: 35
Common mistake
Adding order instead of order.total.
Try this
Count the unpaid orders too.
Source
examples/ex-029-03-objects-loop.js (repository pending publication)

ex-029-04Strings are iterable Browser-executable JavaScript

for...of visits each character.

const code = "A1B2C3";
let letters = "";
let digits = 0;
for (const ch of code) {
  if (ch >= "0" && ch <= "9") digits++;
  else letters += ch;
}
console.log(letters, digits);
Sample input
None
Expected output
ABC 3
Common mistake
Using code.length with for...of; it is not needed.
Try this
Count vowels in a word.
Source
examples/ex-029-04-string-iteration.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Values, not keys

Replace for...in with for...of.

const prices = [4, 6, 10];
let total = 0;
for (const p in prices) {
  total += p;
}
console.log("Total:", total);

Numbered list

Use entries() for index and value.

const guests = ["Ada", "Grace", "Linus"];
// TODO: print "1. Ada", "2. Grace", "3. Linus" with for...of and entries()

Low-stock report

Iterate an array of objects and build a report.

const stock = [
  { item: "Pens", qty: 40, min: 20 },
  { item: "Paper", qty: 5, min: 10 },
  { item: "Tape", qty: 2, min: 5 },
  { item: "Glue", qty: 12, min: 5 }
];

09Prediction

Commit to an answer first, then run the real code to compare.

let out = "";
for (const k in ["x", "y"]) out += k;
for (const v of ["x", "y"]) out += v;
console.log(out);

What is printed?

10Debugging investigation

Removing expired coupons skips some

Two expired coupons are next to each other, and only one of them is removed.

const coupons = [
  { code: "SAVE5", expired: false },
  { code: "OLD1", expired: true },
  { code: "OLD2", expired: true },
  { code: "FREESHIP", expired: false }
];
for (let i = 0; i < coupons.length; i++) {
  if (coupons[i].expired) coupons.splice(i, 1);
}
const active = [];
for (const c of coupons) active.push(c.code);
console.log("Active:", active.join(", "));

More cases in the Debugging Detective Laboratory

11Practical scenario

Daily orders dashboard

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

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

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.
  • Avoid for...in for arrays.

16AI learning prompts

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 explanation iterating 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 prediction iterating 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.
Debugging iterating 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 generation iterating 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 review iterating 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.