Iteration
Learn about iteration and loops
Iteration (Loops)
What is iteration?
Iteration means repeating code multiple times using loops. Instead of writing the same code over and over, you can use a loop to run it as many times as needed.
Benefits of iteration?
- Repeat actions without duplicating code
- Process all items in an array or list
- Handle repetitive tasks automatically
- Update game objects every frame
- Scale to handle any number of items
// for loop
for (let i = 0; i < 5; i++) {
console.log("Loop iteration: " + i);
}
// while loop
let count = 0;
while (count < 3) {
console.log("Count: " + count);
count++;
}
// forEach
const gameObjects = ['player', 'guard', 'npc'];
gameObjects.forEach(function(object) {
console.log("Updating: " + object);
});
// for...of loop
for (const object of gameObjects) {
console.log("Object: " + object);
}
What does this code do?
- Uses
forloop to run code exactly 5 times - Uses
whileloop to repeat while condition is true - Uses
forEach()to run function for each array item - Uses
for...ofloop for cleaner array iteration - Shows different loop styles for different situations
// Practical example: update all game objects
const objects = [
{ name: 'player', x: 100 },
{ name: 'guard', x: 200 },
{ name: 'npc', x: 300 }
];
for (let obj of objects) {
obj.x += 5; // Move each object right
console.log(obj.name + " moved to " + obj.x);
}
What does this code do?
- Updates each object in the array one by one
- Uses
for...ofto iterate through the array - Modifies each object’s position by adding 5
- Shows how iteration is essential for game updates
- Processes all game objects in a single loop
Try It Yourself
%%js // CODE_RUNNER: iteration for (let i = 0; i < 3; i++) { console.log(“Iteration: “ + i); } const items = [‘player’, ‘enemy’]; items.forEach(item => console.log(item));