Functions
Scope
A variable is visible in its block and every nested one — but not outside.
Why it exists
If every variable were visible everywhere, any two parts of a program could accidentally spoil each other's data — say, both using a variable i or total. Scope isolates: a function's variable exists only inside it, so you can name variables short and clear without fear of clashes.
Where it's used
- Functions' local variables: each function has its own
total,result,i. - A loop counter
for (let i = …)that doesn't "leak" outside. - Closures: an inner function sees the outer function's variables.
Syntax
const outer = 1;
{
const inner = 2;
outer; // visible
}
inner; // ReferenceErrorExamples
const tax = 0.2;
function withTax(price) {
return price * (1 + tax);
}
withTax(100); // → 120function demo() {
if (true) {
const inside = 1;
}
return typeof inside;
}
demo(); // → "undefined"const doesn't leave its blockconst name = "global";
function show() {
const name = "local";
return name;
}
show(); // → "local"let total = 0;
function add(n) {
total += n;
}
add(5);
total; // → 5Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
Scopes nest inside each other like Russian dolls: global (the whole file), function scopes, block scopes { } — the bodies of if, for, or just curly braces.
When code uses a variable, JavaScript looks for it in the current scope, then the enclosing one, then further out — up to global. Found it — uses it; didn't — ReferenceError. It can't look down, into nested scopes.
let and const live in the block where they're declared. The old var ignores blocks and lives in the whole function — the source of many surprises.
Declare a variable with the same name in an inner scope and it shadows the outer one: inside, only the new one is visible.
Scope is decided by where a function is written, not where it's called from — which is why a function can "carry" variables with it (a closure).
Traps
How it differs from…
- Closure
A closure follows from scope: a function remembers the scope it was written in.
When to pick something else
Don't move variables into a shared (global) scope "so they're easy to reach from anywhere". Declare each variable in the narrowest scope where it's needed, and pass data through parameters and return values.