Block Scope
What you'll learn: How variables declared inside code blocks (like if-statements and loops) have limited visibility in many programming languages.
What Is Block Scope?
A block is any section of code surrounded by curly braces {}, such as the body of an if statement, while loop, or for loop. In languages that support block scope, variables declared inside a block only exist within that block—they're born when the block starts and disappear when it ends.
Think of a block like a room in a house. A sticky note you place on a wall inside that room only exists in that room. Once you leave and close the door, you can't see or use that sticky note anymore.
How It Works
When you declare a variable inside a block:
- It's only accessible within that block and any nested blocks inside it
- It doesn't exist before the block begins
- It's destroyed when the block completes
For example, if you declare a variable inside an if statement's body, you cannot use that variable after the if statement ends. Similarly, a variable declared in a loop's body is recreated with each iteration and vanishes when the loop finishes.
Why It Matters
Block scope helps prevent bugs by:
- Limiting where variables can be accidentally changed
- Making code easier to understand (you know exactly where a variable lives)
- Avoiding naming conflicts between different parts of your code
Key Takeaway: Block scope confines variables to the code block (like an if-statement or loop body) where they're declared, making them invisible and inaccessible outside that block.