JavaScript Scope
Learn how variable scope works in JavaScript, including global scope, function scope, block scope, lexical scope, and best practices.
Reading Time
18 min
Lesson
Lesson 11 of 48
What is Scope?
Scope determines where a variable can be accessed in your program. It controls the visibility and lifetime of variables. Understanding scope helps you avoid bugs and write clean, maintainable code.
Why Learn Scope?
- Avoid variable conflicts
- Write cleaner code
- Understand function behavior
- Debug applications easily
- Master closures later
Global Scope
A variable declared outside any function or block belongs to the global scope. It can be accessed from anywhere in the program.
Global Scope Example
Console Output
Click “Run” to see the console output here.
Function Scope
Variables declared inside a function can only be accessed within that function. They are not available outside the function.
Function Scope Example
Console Output
Click “Run” to see the console output here.
Block Scope
Variables declared using let and const are block-scoped. They exist only inside the block where they are declared.
Block Scope Example
Console Output
Click “Run” to see the console output here.
var is Not Block Scoped
Unlike let and const, variables declared using var ignore block scope and remain accessible outside the block.
var Example
Console Output
Click “Run” to see the console output here.
Lexical Scope
Lexical scope means that inner functions can access variables declared in their parent functions.
Lexical Scope Example
Console Output
Click “Run” to see the console output here.
Variable Shadowing
Variable shadowing happens when a variable declared inside a function or block has the same name as an outer variable.
Variable Shadowing Example
Console Output
Click “Run” to see the console output here.
Types of Scope
| Scope | Accessible From |
|---|---|
| Global Scope | Entire Program |
| Function Scope | Inside Function Only |
| Block Scope | Inside Block Only |
| Lexical Scope | Parent Scope |
Common Mistake
Avoid using var in modern JavaScript because it ignores block scope and can introduce unexpected bugs. Prefer let and const.
Best Practices
Always declare variables with const by default. Use let only when reassignment is required. Avoid global variables whenever possible.
Summary
JavaScript provides global scope, function scope, block scope, and lexical scope. Understanding scope is essential for writing reliable JavaScript applications.