What is a variable's scope?
A variable's scope is the specific part of your code where that variable is "visible" and can be used. If you try to access or change a variable outside of its scope, the computer will not know what you are talking about and will throw an error.
Think of it like an inside joke among a small group of friends. If you tell the joke to that specific group (the local scope), everyone laughs. If you tell it to a stranger on the street (outside the scope), they will just be confused. In programming, scope tells the computer exactly where a variable's name holds meaning.
Global vs. Local Scope
The two most common types of scope are global and local. A global variable is created at the very top of your program, outside of any functions. It can be seen and used anywhere in your code. A local variable is created inside a specific function or block of code. It only exists while that specific function is running, and it disappears the moment the function finishes.
Why do we use scope?
Scope keeps our programs organized and prevents accidental changes to data. If every variable were global, a large program might have thousands of variables. You might accidentally reuse a common name like or , unintentionally overwriting data from another part of your program. By keeping variables local to the functions that need them, we isolate our code into safe, manageable chunks.
Where students slip up: Shadowing
A common mistake is creating a local variable with the exact same name as a global variable. This is called "shadowing." When you do this, the function will only use the local version, ignoring the global one. Students often expect the global variable to update, but only the temporary local variable is changing. When the function ends, the local variable is destroyed, and the global variable remains completely unchanged.
Worked through
Consider the following Python code:
def add_five(): return
print(add_five()) print()
What will be printed to the screen, and why?
The code will print 10, then 10.
Here is why: The first line creates a global variable and sets it to 10. Inside the add_five function, a new, completely separate local variable also named is created and set to 5. The function returns this local plus 5 (which is 10), so the first print statement outputs 10. However, this local is destroyed when the function finishes. The global was never touched. So, when the second print statement asks for , it looks at the global scope, sees the original 10, and prints 10 again.
Questions students ask
Ask about this topic
Where this comes from: Khan Academy: Intro to JS - Variables and Scope · OpenStax: Computer Science Principles - Data and Variables
See also