JavaScript Scope
JS
In JavaScript, scope refers to where variables are accessible. In simpler terms, it’s about which parts of your code can “see” or use your variables.
Types of JavaScript Scope:
There are mainly three types of scopes:
- Global Scope
- Local (Function) Scope
- Block Scope
1. Global Scope
- Variables defined outside any function or block.
- Accessible from anywhere in your JavaScript code.
2. Local (Function) Scope
- Variables defined inside a function.
- Accessible only within that function.
3. Block Scope
- Variables defined with let or const inside blocks (loops, conditionals).
- Only accessible within that block.
Example with all scopes:
combined practice example to clearly show Global, Local, and Block scopes together: