1. Global Variables
A global variable is declared outside of any function and can be accessed from anywhere in the code (inside or outside functions).
Example:
let globalVar = "I am global";
function showGlobal() {
console.log(globalVar); // Can access globalVar
}
showGlobal();
console.log(globalVar); // Also accessible here
2. Local Variables
A local variable is declared inside a function (or block using let
/const
) and can only be accessed within that function or block.
✅ Example:
function showLocal() {
let localVar = "I am local";
console.log(localVar); // OK
}
showLocal();
// console.log(localVar); // Error: localVar is not defined
Block Scope with let
and const
Variables declared with let
or const
are block-scoped, which means they're only accessible within { }
braces.
if (true) {
let blockVar = "Inside block";
console.log(blockVar); // OK
}
// console.log(blockVar); // Error
Note on var
var
is function-scoped but not block-scoped.
function testVar() {
if (true) {
var x = 10;
}
console.log(x); // Works: x is function-scoped
}
testVar();
Comparison Table
Type | Scope | Accessible From | Keyword |
---|---|---|---|
Global | Entire script | Anywhere |
var , let , const (outside) |
Local | Function/Block | Only inside its block |
let , const , var (inside) |
Summary
- Global Variable = Accessible anywhere in the file.
- Local Variable = Accessible only inside the function or block where it’s declared.
Top comments (0)