StoicBuilder

HandbookI the LudusScope

Ithe Ludus, Read code

Scope

1 min readUpdated 28 November

In plain words

Scope is the part of the code where a variable exists, so a name created inside a function or block can't be seen outside it.

Where you see it

Curly braces mark the edges. When the agent creates discount inside an if block and uses it further down, you get "discount is not defined", even though you can see it a few lines up.

src/lib/checkout.tsbrowser
function getTotal(subtotal: number, promo: boolean) { if (promo) { const discount = 5; // exists only inside these braces } return subtotal - discount; // error: discount is not defined here}
Declare a name where every line that needs it can see it.

What goes wrong

  1. A name declared one block too deep

    const and let only live inside the nearest pair of braces. Declare the variable above the if, so the lines below can reach it.

  2. Two variables with the same name

    A user inside a function hides a different user outside it. The code reads the inner one, and you spend an hour wondering why it's the wrong person.

  3. Keeping the current user at the top of a server file

    A variable outside any function outlives the request, so visitors share it. One person's data can turn up in someone else's response.

    let currentUser; // top of app/api/orders/route.ts

What to tell your agent

Copy this into Lovable, Bolt, Cursor or any agent
Declare each variable in the smallest block that needs it, and don't reuse a name that already exists further out. On the server, keep anything about the current user or request inside the request handler, never at the top of the file.

Quick check

Sign in to earn +10 XP for it

An API route stores the logged-in user in a variable at the top of the file. What can happen?

Got a prompt that touches scope?

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

Check your own prompt

Free, no sign-up.