Where a variable is declared determines its scope: outside functions is global, inside is local
A variable’s scope — where it can be accessed — is set by where it is declared. A variable declared outside all function blocks is global and readable/writable from any function. A variable declared inside a function block is local: it exists only within that function and is deallocated when the function returns. To persist state across repeated calls of a render loop (a counter, a position, a speed), the variable must be global; the classic bug is declaring such a variable inside the loop, where it is recreated and reset every call, preventing animation. The mirror bug is a local variable accidentally shadowing a global of the same name. Scope errors are among the most common bugs, so a misbehaving program is one of the first things to check. A useful convention is marking globals visually (e.g. an underscore prefix, _num).
Examples
p5.js — let x = 0; before setup() is global and survives across frames; inside draw() x = x + 2; circle(x,200,30); accumulates, while let r = random(255); is local and new each frame. Bug: putting let x = 0; inside draw() resets it every frame so the circle never moves. Processing — global int _diam = 10; outside setup/draw persists; declaring it inside draw() resets it each frame.
Assessment
Find and fix the scope bug: void draw(){ int counter = 0; counter++; ellipse(counter,150,20,20); } — explain what it does visually and why. Separately, a learner puts let x = 0; inside draw() and the circle won’t move; explain and fix.