Advanced
Scope
Where variables are visible: global, function, block.
1. Explanation
Scope determines where a variable can be accessed. Global scope = anywhere. Function scope = inside the function. Block scope = inside { } (only for let/const). Inner scopes can read outer variables (closure), but outer scopes cannot read inner ones.
2. Example
Try it yourself
Console
Click Run to see output.
3. Expected output
output
I'm everywhere inside outer inside block4. Common mistakes
- ✗Polluting the global scope by forgetting let/const
- ✗Expecting var to be block-scoped — it isn't
- ✗Shadowing a variable accidentally with the same name in an inner scope
5. Practice questions
- Demonstrate block scope by declaring 'let x' inside an if-block
- Show how var leaks out of a for-loop but let doesn't
- Write a function that captures an outer variable