JavaScript Scope Explained | Global, Function, Block & Lexical Scope
Have you ever seen an error like this?
Or wondered why a variable works inside one function but not another?
The answer lies in JavaScript Scope.
Scope determines where a variable or function can be accessed within your code. Understanding scope is essential for writing clean, predictable, and bug-free JavaScript applications.
In this guide, we'll explore the four main types of scope in JavaScript with practical examples.
What Is Scope?
Scope defines the accessibility or visibility of variables, functions, and objects in different parts of your program.
In simple words:
Scope answers the question: "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
Let's understand each one.
1. Global Scope
A variable declared outside any function or block belongs to the Global Scope.
Example:
const website = "TechCampPro";
function showWebsite() {
console.log(website);
}
showWebsite();
console.log(website);
Output
Since website is globally scoped, it can be accessed anywhere in the program.
Why Avoid Too Many Global Variables?
Using too many global variables can:
- Cause naming conflicts
- Make debugging difficult
- Increase the risk of accidental changes
❌ Bad Example
Imagine another file also creates:
Now your application may behave unexpectedly.
2. Function Scope
Variables declared with var, let, or const inside a function are only accessible within that function.
Example:
function greet() {
const message = "Hello!";
console.log(message);
}
greet();
console.log(message);
Output
The variable message exists only while the function is executing.
3. Block Scope
A block is any code enclosed in curly braces {}.
Variables declared with let and const are block-scoped.
Example:
if (true) {
let age = 25;
const city = "Lahore";
console.log(age);
console.log(city);
}
console.log(age);
console.log(city);
Output
25
Lahore
ReferenceError
ReferenceError
The variables only exist inside the block.
What About var?
Unlike let and const, var ignores block scope.
Example:
if (true) {
var language = "JavaScript";
}
console.log(language);
Output
This is one reason modern JavaScript prefers let and const.
4. Lexical Scope
Lexical Scope means that a function can access variables from its outer scope.
Example:
const language = "JavaScript";
function outer() {
const framework = "React";
function inner() {
console.log(language);
console.log(framework);
}
inner();
}
outer();
Output
The inner() function can access variables from its own scope and all outer scopes.
This behavior is called Lexical Scope.
Scope Chain
When JavaScript looks for a variable, it follows the Scope Chain.
Example:
const company = "TechCampPro";
function one() {
const course = "JavaScript";
function two() {
const lesson = "Scope";
console.log(company);
console.log(course);
console.log(lesson);
}
two();
}
one();
JavaScript searches in this order:
Current Scope
↓
Parent Scope
↓
Global Scope
If the variable isn't found anywhere, JavaScript throws a ReferenceError.
Real-World Example
const apiUrl = "https://api.example.com";
function fetchUsers() {
const endpoint = "/users";
console.log(apiUrl + endpoint);
}
fetchUsers();
Here:
apiUrl is global.
endpoint exists only inside fetchUsers().
Scope and Closures
Closures work because of Lexical Scope.
Example:
function createCounter() {
let count = 0;
return function () {
return ++count;
};
}
const counter = createCounter();
console.log(counter());
console.log(counter());
console.log(counter());
Output
The returned function remembers the count variable even after createCounter() has finished executing.
Common Mistakes
❌ Accessing Block Variables Outside the Block
if (true) {
let x = 10;
}
console.log(x);
Result:
❌ Using var Instead of let
for (var i = 0; i < 3; i++) {}
console.log(i);
Output
With let:
for (let i = 0; i < 3; i++) {}
console.log(i);
Output
Best Practices
✅ Use const by default.
✅ Use let only when a variable needs to change.
✅ Avoid var in modern JavaScript.
✅ Keep variables in the smallest possible scope.
✅ Minimize global variables.
Interview Tips
If an interviewer asks:
What is Scope in JavaScript?
You can answer:
Scope defines where variables and functions are accessible in a program. JavaScript provides Global Scope, Function Scope, Block Scope, and Lexical Scope. Variables declared with let and const are block-scoped, while var is function-scoped. Lexical Scope allows inner functions to access variables from their parent scopes.
Key Takeaways
- Scope controls where variables can be accessed.
- Global variables are accessible everywhere.
- Function-scoped variables exist only inside the function.
let and const create block-scoped variables.
var is function-scoped and ignores block boundaries.
- Lexical Scope enables closures.
- The Scope Chain searches from the current scope outward.
Conclusion
JavaScript Scope is one of the core concepts every developer should master. Whether you're building web applications, debugging issues, or preparing for interviews, understanding how variables are scoped will help you write safer and more maintainable code.
Once you understand Scope, concepts like Closures, Execution Context, and Hoisting become much easier to understand.