Scope
In real life, access matters. Some information is public, some is private, and some is limited to a specific place.
In JavaScript, scope decides where variables and functions can be accessed and used.
What Is Scope?
Scope defines the area of a program where a variable is available. If a variable is outside its scope, JavaScript cannot access it.
Understanding scope helps prevent bugs and unexpected behavior.
Global Scope
A variable declared outside any function or block belongs to the global scope.
let siteName = "Dataplexa";
function showName() {
console.log(siteName);
}
Global variables can be accessed from anywhere in the program.
Local (Function) Scope
Variables declared inside a function are local to that function. They cannot be accessed outside.
function greet() {
let message = "Hello";
console.log(message);
}
greet();
Trying to access message outside the function will cause an error.
Block Scope
Variables declared with let and const
inside a block { } have block scope.
if (true) {
let count = 5;
console.log(count);
}
The variable count is only available inside the block.
Why var Is Different
Variables declared with var do not have block scope.
This can lead to confusion and bugs.
if (true) {
var value = 10;
}
console.log(value);
This is one reason why let and const are preferred.
Real-World Example
Imagine a company system:
- Global data → accessible to everyone
- Department data → accessible only within the department
- Personal data → accessible only to the owner
Scope in JavaScript works in a very similar way.
Common Beginner Mistakes
- Using too many global variables
- Confusing block scope with function scope
- Using
varunintentionally
Always limit variable scope as much as possible.
Thumb Rules
- Use
letandconstinstead ofvar - Keep variables inside the smallest scope needed
- Avoid polluting the global scope
- Clear scope improves readability and safety
More on Scope Later
This lesson focused on how scope works at a basic level.
Some advanced behavior is intentionally covered later.
- Variable behavior during execution is explained in Lesson 10 (Hoisting)
- Scope chains and execution context are discussed in Lesson 43 (Execution Context)
What Comes Next?
Now that you understand where variables live, the next step is learning how JavaScript processes them during execution.
In the next lesson, we will learn about hoisting.