StoicBuilder

HandbookI the LudusLoops

Ithe Ludus, Read code

Loops

1 min readUpdated 28 November

In plain words

A loop runs the same piece of code again and again, usually once for every item in a list, until there's nothing left.

Where you see it

Your Chirp feed shows 20 posts, but the code only describes one. A loop runs that description once per post. Cart totals, email batches and "mark all as read" work the same way.

src/lib/cart.tsbrowser
let total = 0; for (const item of order.items) { total += item.price * item.quantity;}
One instruction, run once for every item in the order.

What goes wrong

  1. Off by one with <=

    Lists count from 0, so three items sit at positions 0, 1 and 2. Looping up to <= length reads one past the end and gets undefined.

    for (let i = 0; i <= items.length; i++)
  2. A loop that never stops

    If the stop condition can never become true, the browser tab freezes and stops responding.

    while (page < totalPages) { fetchPage(page); } // page never grows
  3. One database call per item

    A loop that asks Supabase about each of 200 posts makes 200 trips. It feels fine with test data and crawls with real users.

What to tell your agent

Copy this into Lovable, Bolt, Cursor or any agent
Check every loop in this file for off-by-one errors and for a stop condition that is always reached. If a loop calls the database or an API once per item, rewrite it to fetch everything in one request and tell me how many calls that saves.

Quick check

Sign in to earn +10 XP for it

A loop over a 3-item order uses i <= items.length. What happens?

Got a prompt that touches loops?

Paste it. You get a better prompt first, then the cards that explain it.

Check your own prompt

Free, no sign-up.