JavaScript Scope

JavaScript Scope (Beginner → Advanced)
Scope in JavaScript defines where a variable can be accessed in your code.
Understanding scope is critical for writing bug-free JS, especially with var, let, const, functions, and closures.
What is Scope in JavaScript?
Scope determines the visibility and lifetime of variables.
In simple words:
Where can I use this variable?
Types of Scope in JavaScript
JavaScript has four main types of scope:
Global Scope
Function Scope
Block Scope
Lexical Scope
Global Scope
Definition
Variables declared outside any function or block
Accessible anywhere in the program
- Too many global variables → bad practice
Function Scope
Definition
Variables declared inside a function
Accessible only inside that function
varis function-scoped
Block Scope {} (Very Important)
Introduced with ES6 using let and const.
Definition
Variables declared inside
{}Accessible only inside that block
letandconstare block-scopedvaris not block-scoped
var vs let vs const (Scope Comparison)
| Keyword | Scope | Re-declare | Re-assign |
|---|---|---|---|
var | Function | Yes | Yes |
let | Block | No | Yes |
const | Block | No | No |
Lexical Scope (Interview Favorite)
Inner functions can access variables of outer functions.
- Scope is decided by where code is written, not executed
Scope Chain
JavaScript looks for variables in this order:
- JS climbs the scope chain
Hoisting and Scope
var Hoisting
let / const Hoisting
- Temporal Dead Zone (TDZ)
Closures (Advanced Scope Concept)
A function that remembers variables from its outer scope, even after the outer function finishes.
Used in:
Data hiding
Callbacks
React hooks
Common Scope Mistakes
- Using
varinstead oflet Polluting global scope- Assuming block scope for
var Accessing variable before declaration
Interview Questions (Must Prepare)
What is scope in JavaScript?
Difference between
var,let, andconstWhat is block scope?
What is lexical scope?
What is scope chain?
Explain closures
Real-Life Importance
Prevents bugs
Avoids variable conflicts
Essential for async JS
Required for frameworks (React, Node.js)
Summary
- Scope controls variable accessibility
var→ function scopelet&const→ block scope- JS uses lexical scoping
- Closures depend on scope
- Extremely important for modern JavaScript & interviews
