Scope
The rules that decide where a variable can be used in your code.
What is it?
A variable can't be used everywhere in your program. The area where it's usable is its scope.
JavaScript decides scope by where a variable is declared in the code. This is lexical scope. A variable declared inside a function is only usable in that function (and anything nested in it), and disappears when the function finishes.
Explain like I'm 10
Scope is like rooms in a house. Something you leave in the kitchen is only reachable from the kitchen or rooms inside it, not from every room in the house.
Examples
Function scope
function greet() {
const message = "Hello!";
console.log(message); // works fine, "message" is in scope here
}
greet();
console.log(message); // ❌ Error: message is not defined out hereBlock scope with let/const
if (true) {
const secret = "hidden";
console.log(secret); // works
}
console.log(secret); // ❌ Error: secret is not definedHow it works
To find a variable, JavaScript checks the current block, then the block around it, and so on outward. This is the scope chain. If it reaches the outermost level without finding the variable, it throws an error.
The lookup depends only on where the code was written, not the order it runs in.
Global scope
└── Function scope
└── Block scope (if/for/while)
Lookup direction: inner → outer, never outer → innerWhy does it exist?
Without scope, every variable would be visible everywhere. In large programs, names would collide and you couldn't tell what any piece of code depends on. Scope keeps variables where they're relevant.
When to use it
You reason about scope when deciding where to declare a variable, debugging a "not defined" error, or working out why a variable inside a function isn't visible outside it.
When not to use it
For a variable used in one small, self-contained block, scope needs little thought. It becomes a source of confusion (and bugs) once a program is big enough to reuse the same names in many places.
Common mistakes
Assuming a variable declared inside an
ifblock is available outside of it.Accidentally creating a global variable by forgetting
let/const/var.Being surprised that two functions can each have their own separate variable with the same name, with no conflict.
Practice exercises
- Easy:
Declare a variable inside a function and try (and fail) to log it outside the function. Observe the error.
- Medium:
Write two functions that each declare a local variable with the same name, and show they don't interfere with each other.
- Hard:
Explain, in writing, why a variable declared with
letinside aforloop is not accessible after the loop ends.
Interview questions
What is scope in JavaScript?
The rules for where a variable can be used. A variable declared inside a function is usable there and in anything nested in it, but not outside.
What does it mean that JavaScript uses lexical scope?
Where a variable is visible depends on where it's written in the source, not on which function calls which or the order code runs in.
What's the difference between global scope, function scope, and block scope?
Global scope is visible everywhere. Function scope covers a function and anything nested in it. Block scope, from let/const, covers the nearest {}: an if, a for or a bare block.
What is the 'scope chain', and how does variable lookup use it?
The engine looks for a variable in the current scope, then the scope around it, and so on outward until it finds it, or reaches global scope and throws a ReferenceError. It only searches outward, never inward.
What does this log? `const a = 1; function outer() { const a = 2; function inner() { console.log(a); } inner(); } outer();`
2. inner has no a, so the lookup moves out to outer's scope, finds a = 2 and stops before reaching the global a.
What does this log? `console.log(x); var x = 5;`
undefined, not a ReferenceError. var is hoisted to the top of its function (or global) scope and set to undefined. Only the assignment x = 5 stays in place, so reading x earlier gives undefined.
What does this log? `console.log(y); let y = 5;`
It throws ReferenceError: Cannot access 'y' before initialization. let/const are hoisted but not set to undefined; they're in the "temporal dead zone" until their declaration runs, and touching them there is an error.
What's the practical difference between `var` being function-scoped and `let`/`const` being block-scoped?
A var declared in an if or for block leaks out to the whole enclosing function. A let/const only exists inside that {} block.
What does this log? `for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); }`
3, 3, 3. var gives one shared i for all iterations, and by the time the callbacks run, the loop is done and i is 3.
What does this log, and why does it differ from the `var` version? `for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); }`
0, 1, 2. let creates a new i for each iteration, so each closure captures its own value.
What happens if you forget `let`/`const`/`var` when assigning to a new variable name inside a function?
In non-strict mode, JavaScript silently creates a global variable. The assignment works, but the variable is now visible everywhere.
What does this log? `function foo() { bar = 5; } foo(); console.log(bar);`
5 in non-strict, non-module code: the undeclared assignment creates a global. In strict mode or an ES module it throws a ReferenceError, one reason those are a safer default.
What does this log? `if (true) { const secret = "hidden"; } console.log(secret);`
ReferenceError: secret is not defined. const (like let) is block-scoped, so secret only exists inside the if block.
What is variable shadowing?
Declaring a variable with the same name as one in an outer scope. Inside the inner scope, the new one hides (shadows) the outer one, without changing it.
What does this log? `let x = "outer"; function show() { let x = "inner"; console.log(x); } show(); console.log(x);`
"inner" then "outer". The inner x shadows the outer one inside show; the outer x is untouched.
Does an ES module's top-level scope behave like the classic global scope from a `<script>` tag?
No. Each module has its own file-level scope, and its top-level const/let/function aren't visible to other files unless exported. In a classic script, top-level var/function declarations become properties of the shared global object.
What was an IIFE used for before `let`/`const` existed, and why is it less necessary now?
An Immediately Invoked Function Expression created a private function scope on demand, faking the block scope var lacked, to keep helper variables out of the global scope. let/const now give real block scope without wrapping code in a function.
What does this log? `(function () { var secret = "hidden"; })(); console.log(typeof secret);`
"undefined". secret exists only inside the IIFE's function scope and was never visible outside.
How is 'scope' different from 'execution context'?
Scope is static: which variables code can see, fixed by where it's written. An execution context is the runtime state of one function call: its this, its arguments and the variables created for that call.
Does JavaScript use lexical scoping or dynamic scoping?
Lexical. A function's scope is fixed by where it's defined, never by where or how it's called.
What does this log? `let value = "global"; function a() { console.log(value); } function b() { let value = "local"; a(); } b();`
"global". a is called inside b, but its scope was fixed where it was defined, at the top level, where only the global value is visible. With dynamic scoping it would print "local".
Is a caught error in a `catch` block scoped like a regular `let` declaration?
Yes. The err in catch (err) { ... } exists only in that catch block and doesn't clash with an outer variable of the same name.
What does this log? `function greet(name, greeting = "Hello, " + name) { console.log(greeting); } greet("Amara");`
"Hello, Amara". Default parameter expressions can see parameters declared before them, so greeting's default can use name.
Why does scope matter more as a codebase grows, even though a single small function rarely needs to think about it?
Without scope, every name would need to be unique across the whole program. Scope lets short, obvious names (i, result, data) be reused safely in unrelated functions, since each sees only its own.
Why is it usually a bad sign to see a variable declared far from where it's used, at a broader scope than necessary?
The wider the scope, the more code can accidentally read or overwrite it, and the harder it is to know its value at any point. Narrow scopes limit how much code you must check when debugging.
What does this log? `console.log(typeof undeclaredVar); console.log(undeclaredVar);`
"undefined", then a ReferenceError. typeof is safe on undeclared names, but reading the name directly throws, since it isn't declared in any visible scope.
What is the relationship between scope and closures?
A closure is a function defined inside another that keeps access to the outer scope after the outer function returns. It's the scope chain outliving the call that created it, not a separate mechanism.
How would you debug a `ReferenceError: x is not defined`?
Check that x is declared in a scope that contains the line using it. Usual causes: a typo, a let/const declared inside a block or later in the same block (temporal dead zone), or a parameter or import that was never wired up.
Can two completely separate functions each declare a local variable with the same name without conflict?
Yes. Each call gets its own scope, so let total in two unrelated functions are separate variables that never interact.
Why can't you use `const` for a traditional counting `for` loop like `for (const i = 0; i < 10; i++)`?
i++ reassigns i, which const forbids, so it throws a TypeError on the first increment. for...of can use const because each iteration gets a new binding instead of reassigning one.
Are function declarations hoisted the same way `var` is?
Further. A function declaration is hoisted with its whole definition, so it can be called before its line. A var is hoisted only as undefined, so calling it early would fail.
Does declaring the same `var` name twice in the same scope cause an error?
No. The redeclaration is ignored and the variable keeps its value. With let/const it throws a SyntaxError.
What's the scope of a function's parameters relative to its body?
Parameters have their own scope wrapping the body. The body can read and reassign them, and a let/const/var in the body with the same name shadows the parameter.