JavaScript scope determines where variables and functions are visible and accessible in your code. JavaScript uses lexical scoping, meaning inner blocks and functions can read variables defined in outer scopes based on where the code is written.
var, let, const, and parameters) are private to that function.let and const bindings declared inside { ... } blocks such as if, for, or while stay hidden outside those braces.flowchart TD
Inner["Inner Function (localVar)"] -- "Not found locally, look up" --> Outer["Outer Function (outerVar)"]
Outer -- "Not found here, look up" --> Global["Module / Global Scope (config)"]
A closure happens when an inner function remembers and keeps access to variables from its outer function even after that outer function has finished running.
function createCounter(startValue = 0) {
let count = startValue; // Private via closure
return {
increment() {
count += 1;
return count;
},
getValue() {
return count;
},
};
}
const pageViews = createCounter(10);
console.log("Next view:", pageViews.increment()); // 11
console.log("Current:", pageViews.getValue()); // 11
window creates name collisions across scripts. Keep modules isolated and declare variables in the smallest scope needed.let user identically to an outer const user hides the outer variable inside that inner block.Lexical scope depends on where a function is defined in source code, whereas dynamic scope depends on where it is called. JavaScript uses lexical scope (except for this, which depends on call site).
No, the scope chain flows outward only. Outer code cannot reach inward to inspect local function variables.
Closures power private state, event handlers, debounced search inputs, factory functions, and React hooks.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.