Scope in JavaScript refers to the context in which variables are accessible. It determines which part of the code can access and manipulate a particular variable.
Types of Scope in JavaScript:
1. Global Scope:
- Variables declared outside any function or block.
- Accessible anywhere in the code.
javascriptCopyEditlet globalVar = 'I am global';
function example() {
console.log(globalVar); // Accessible here
}
console.log(globalVar); // Accessible here too
2. Local/Function Scope:
- Variables declared inside a function using
var
,let
, orconst
. - Accessible only within that function.
javascriptCopyEditfunction example() {
let localVar = 'I am local';
console.log(localVar); // Accessible here
}
console.log(localVar); // Error: localVar is not defined
3. Block Scope (ES6):
- Introduced with
let
andconst
. - Variables declared inside a block
{}
are only accessible within that block.
javascriptCopyEdit{
let blockVar = 'I am block-scoped';
console.log(blockVar); // Accessible here
}
console.log(blockVar); // Error: blockVar is not defined
Note: var
does not have block scope. It is function-scoped.
4. Lexical Scope (Closures):
- A function can access variables from its outer scope where it was defined.
- Inner functions have access to variables of outer functions.
javascriptCopyEditfunction outer() {
let outerVar = 'I am outer';
function inner() {
console.log(outerVar); // Accessible due to lexical scope
}
inner();
}
outer();
Scope Chain:
- When a variable is accessed, JavaScript looks for it in the current scope.
- If not found, it moves up to the outer scope, continuing until it reaches the global scope.
- If still not found, it throws an error.
javascriptCopyEditfunction example() {
let a = 'local';
function inner() {
console.log(a); // Looks for 'a' in inner scope -> not found, moves to outer scope -> found
}
inner();
}
example();
Summary Table:
Scope Type | Declared with | Accessible from |
---|---|---|
Global Scope | var , let , const | Anywhere in the program |
Function Scope | var , let , const | Inside the function |
Block Scope | let , const | Inside the block {} |
Lexical Scope | (Any) | Inner functions can access outer variables |
Understanding scope is crucial to avoid variable conflicts, manage data properly, and write clean, bug-free JavaScript.