Beginner Topic 15 of 54 Programming Fundamentals
Scope
The region of a program where a name is visible and accessible.
How it works
Scope rules decide where in a program a name is visible: block, function, module or global. Inner scopes can read names from outer scopes, and lexical scoping resolves a name by where the code is written rather than where it is called. When two scopes define the same name, the inner one shadows the outer one. Lifetime is related but separate: a variable may exist longer than its name is visible.
Step-by-step walkthrough
- Global names are visible everywhere.
- A function adds its own local names.
- A block inside it adds a still narrower scope.
- Lookup starts at the innermost scope and moves outward.
- An inner name can shadow an outer one with the same name.
- Locals vanish when their scope ends.
Where it is used
Keeping loop variables private, avoiding naming collisions between modules, limiting how much code can change a value and implementing closures all depend on scope. Smaller scopes make code easier to reason about.
Common pitfall
Accidentally shadowing a variable, assigning to a global when you meant to create a local, and relying on globals make behavior depend on hidden state. Declare variables in the narrowest scope that works and pass data explicitly through parameters.
Where it fits in the course
Scope is topic 15 of 54 in Programming Fundamentals, rated Beginner. It follows Return Values. The next topic is Comments and Documentation.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Programming Fundamentals quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Programming Fundamentals quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Scope?
Where do people use Scope?
What is the most common mistake with Scope?
What should I learn before this topic?
How can I practice it?
Is Scope hard to learn?
How long does it take to learn Scope?
Which topics are related to Scope?
What should I study after Scope?
Related topics
- Return Values (Programming Fundamentals)
- Comments and Documentation (Programming Fundamentals)
- Parameters and Arguments (Programming Fundamentals)
- Debugging Basics (Programming Fundamentals)