Scope is "who can see which variable"
Picture a house. What you leave in your bedroom can't be seen from the kitchen. Variables work the same way: each one lives in a "room" and is only visible from inside. We call that room the scope.
Getting this saves you from the classic "but I declared that variable, why does it say it doesn't exist?". Spoiler: it does exist, just in another room.
Global scope
A variable declared outside of any function or block is global: it's visible from anywhere in the program. Convenient, but risky if you overdo it: anyone can touch it.
const planet = "Earth"; // global
function show() {
console.log(planet); // accessible here
}
Local scope (function)
Variables declared inside a function only exist there:
function compute() {
const internal = 42;
return internal;
}
// console.log(internal); // ❌ Error: internal doesn't exist outside
Block scope
With let and const, every pair of braces { } (an if, a for...) creates
its own mini-room:
if (true) {
let message = "hi";
console.log(message); // ✅ "hi"
}
// console.log(message); // ❌ Error: outside the block it doesn't exist
⚠️ Classic trap:
vardoes not respect block scope, only function scope. Avardeclared inside anifleaks outside the block and gives you surprises. That's why today we useletandconst: they respect the room.
Examples
The global is visible from inside; the local stays locked in its function
const global = "I'm global";
function demo() {
const local = "I'm local";
console.log(global); // accessible
console.log(local); // accessible
}
demo();