Imagine you are making a sprite (a little character on the screen) flap its wings so it looks like it's flying. To flap once, you use a flap block. But you want it to flap ten times! Are you really going to drag out ten flap blocks and stack them up in a tall, wobbly tower?
There is a much tidier way. Computers are brilliant at doing the same thing over and over without ever getting bored. So instead of stacking blocks, we use a special block called a repeat block (some people call it a loop). It wraps around the blocks you want to do again, and a little number tells it how many times.
Instead of flap, flap, flap, flap, flap, flap, flap, flap, flap, flap (phew!) you just say: repeat 10 times: flap. One flap block, tucked inside a repeat block. Same flapping, far less mess.
A repeat block is shaped like a big letter C. It gives the inside blocks a cosy hug! Whatever blocks you drop inside the C get done again and again. The number at the top says how many times to go round.
So this little loop means: move, then turn — and do that whole thing 4 times over. Only two blocks inside, but they run four times each. Tidy!
Here is the clever bit. A square has 4 sides that are all the same, and at every corner you turn the same way. That's a pattern — the same thing, over and over. Perfect for a loop!
Watch the sprite follow repeat 4 times: move forward, turn. Step through it and count the corners. After 4 goes round the loop, the square is finished and the sprite is back where it started.
Without a loop you would need to write move, turn, move, turn, move, turn, move, turn — eight blocks! With a loop it is just two blocks and the number 4. The loop did the repeating for you.
The same trick works for a little floor robot (like a Bee-Bot buzzing across the classroom carpet). To send it round a square tile, you could press forward, turn, forward, turn, forward, turn, forward, turn. Or, if your robot understands loops, you tell it repeat 4 times: forward, turn — and off it goes round the square all by itself. Shorter to type, and much easier to fix if something goes wrong, because there's only one "forward" and one "turn" to check.
This isn't blocks, but it's exactly the same idea written down. The line with the wiggle in it
is the loop, and the block hugged inside it is the console.log that prints a word.
The loop runs the inside 4 times. Press Run and count how
many times "flap!" appears.
Change the 4 to a 10 and run it again. Ten flaps, and you only had to change one little number. That's the magic of a loop: one small number does a lot of work.
Two things trip people up with loops:
And beware a loop that repeats forever: if you never give it a number to stop at, it goes round and round and never stops. Sometimes that's what you want (a heartbeat that beats all day), but usually you want it to finish!