Skip to content

Programming Basics

Scope (Local vs Global)

The idea, in plain English

Scope is about WHERE a variable can be seen and used. A 'global' variable is like an announcement over the school's loudspeaker — every classroom hears it. A 'local' variable is like a note passed around inside just ONE classroom. Kids in other classrooms have no idea it exists, and it disappears once that class ends.

How it works

  1. 1A variable created outside of any function is 'global'. Every function in the file can read it.
  2. 2A variable created INSIDE a function is 'local' to that function. It's a fresh box that only exists while the function is running, then it's thrown away.
  3. 3If a local variable has the SAME name as a global one, the local one wins inside that function. It temporarily 'shadows', or hides, the global — without changing the global's own value at all.

When you'd use it

Think about scope anytime you decide where to put a variable. Keep values local to a function whenever possible, so different parts of a big program don't accidentally step on each other's data. Reach for a global only for things truly needed everywhere, like a shared setting.

Common beginner mistakes

  • Trying to use a local variable outside the function it was created in. It simply doesn't exist out there, and the computer will complain it can't find it.
  • Assuming that changing a local variable also changes a global variable with the same name. It doesn't. They are two separate boxes that just happen to have the same label.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Bonus round result: 150
Global score after: 100

Not sure this is the right topic? See the learning paths → or where this leads →