Iteration
Control Structures · Use loops for game object arrays and animation frames.
Iteration
What it is
Iteration means repeating an action over a sequence of values. JavaScript offers several looping constructs: for for index-based loops, forEach for callback-based iteration over arrays, for...of for value-based iteration, and while for condition-based loops. Each has its own ergonomic sweet spot.
Why it matters
Games are inherently iterative — the game loop runs 60 times per second, and inside each frame you iterate over every active entity. Without efficient looping, a level with dozens of objects would visibly hitch every frame.
How GateGame implements it
The spline() helper uses Array.map() to iterate over each [relX, relY] pair and convert it to pixel coordinates. Inside the engine’s game loop, gameObjects.forEach(obj => obj.update()) runs every frame to advance physics on every active entity. The level-load code uses for...of to iterate the this.classes array and instantiate each entry.
Code Example
// for...of loop over the classes array
for (const obj of this.classes) {
if (obj.class === Npc) {
if (obj.data.interact) {
obj.data.interact();
}
}
}
// Array.map() inside spline() — iterates over coordinate pairs
splinePoints: points.map(([px, py]) => ({
x: Math.round(px * width),
y: Math.round(py * height)
})),
Key Takeaway
Pick the loop that matches the shape of your data:
forEach/mapfor transforming arrays,for...offor cleanly iterating without indexes,whilefor condition-driven work.