Lesson 7
Scope
Scope determines the accessibility (visibility) of variables in different parts of your code.
Variables declared outside any function or block have global scope.
1let globalVar = "I am global";23function test() {4 console.log(globalVar); // Accessible5}67test(); // I am global Avoid too many global variables to keep code clean and avoid conflicts.
Variables declared inside a function are accessible only within that function.
1function greet() {2 let msg = "Hello!";3 console.log(msg); // Accessible4}56greet(); // Hello!7console.log(msg); // Error Function scoped variables cannot be accessed outside the function.
Variables declared with let or const inside a block { } are accessible only within that block.
1if (true) {2 const pi = 3.14;3 let count = 1;4 console.log(pi); // 3.145}67console.log(pi); // Error8console.log(count); // Error Block scope helps prevent accidental access outside the block.
| Scope Type | Declared With | Accessibility | Example |
|---|---|---|---|
| Global Scope | var, let, const | Anywhere in the program | let a = 10; |
| Function Scope | var, let, const | Within the function | function foo() {} |
| Block Scope | let, const | Within the block {} | if (true) { let x; } |
Note: var does not have block scope. It is function-scoped.
- Using var instead of let/const
- Accessing variables outside their scope
- Redeclaring variables in the same scope
- Modifying global variables inside functions
- Scope controls variable visibility.
- let and const provide block scope.
- Use the smallest possible scope.
- Avoid polluting the global scope.
Experiment with different scopes in the editor.
JavaScript
Output
Your output will appear here...
