Looping over collections
Arrays (we meet them in Group 7) live and die by the loop. The classic safe pattern visits every item without running past the end:
const obstacles = ["spike", "pit", "wall"];
for (let i = 0; i < obstacles.length; i++) {
console.log("Obstacle " + i + ": " + obstacles[i]);
}
i runs from 0 to length - 1. The highest valid index is length − 1, so asking for obstacles[4] on a 3-item array gives undefined: a silent bug, not an error.
A newer, cleaner form does the same thing without touching i:
for (const item of obstacles) {
console.log(item);
}
This "for each item" form is what the game uses most when it scans coins, hazards, and ground.
Guards, continue, and breaking out
Inside a loop you often want to skip the current item or stop entirely:
continue: abandon the rest of this round and move to the next item. The ground loop uses it to skip gaps.break: exit the loop completely, now.
for (let i = 0; i < 100; i++) {
if (i === 5) break; // stop at 5
if (i % 2 === 0) continue; // skip even numbers
console.log(i); // prints 1, 3, 5...
}
A guard clause at the top of a loop body (like if (!g.active) continue) keeps the "happy path" code un-nested. Real game loops are full of them, skip inactive objects, skip off-screen objects, skip gaps.