When you need to do something many times — draw 20 stars, check every enemy — you don’t write it 20 times. A loop repeats a block of code for you.
1. The for loop
A for loop repeats a set number of times, counting with a variable (here i). This draws five circles in a row:
function draw() {
cls(1);
for (let i = 0; i < 5; i++) {
circfill(24 + i * 20, 64, 6, 9);
}
}The for has three parts, separated by semicolons:
let i = 0— start the counter.i < 5— keep going while this is true.i++— step the counter (add 1) after each repeat.
So i goes 0, 1, 2, 3, 4, and because each circle uses i for its position (24 + i * 20), they line up across the screen.
2. The while loop
A while loop repeats as long as its condition stays true — handy when you don’t know the exact count up front. You change the condition yourself inside the loop:
function draw() {
cls(1);
let x = 8;
while (x < 120) {
circ(x, 64, 4, 12);
x += 16; // move along; eventually x reaches 120 and the loop stops
}
}Always change the thing you’re testing inside a while (here x += 16). If the condition never turns false, the loop runs forever — GameSpark stops a runaway loop for you, but the game won’t do what you meant.
3. Looping a set number of times
A for loop is the go-to when you know the count. Draw a stack of bars, or spawn ten of something:
function draw() {
cls(1);
for (let i = 0; i < 8; i++) {
rectfill(20, 10 + i * 12, 108, 18 + i * 12, 8 + i);
}
}Each pass uses i for the bar’s height and its color, so one small loop paints eight different rows. Loops really shine over lists — you’ll use for to walk an array in the Arrays lesson.
What you learned
- A
forloop repeats a set number of times, counting with a variable. - Its three parts: start (
let i = 0), keep going (i < 5), step (i++). - A
whileloop repeats while its condition holds — change that condition inside, or it never ends. - Use the counter (
i) inside the loop to vary each repeat.