JavaScript Scope

Closures

Master lexical scope, persistent state, private variables, and one of JavaScript's most powerful concepts.

Understand how functions remember variables from their outer scope even after execution has completed.

What is a Closure?

A closure is created when a function remembers variables from its outer lexical scope.

outer()inner()remembered state

Lexical Scope

Inner functions can access parent variables because scope is determined by where code is written.

outer()inner()remembered state

Why Closures Matter

Closures enable state persistence, encapsulation, private variables, factory functions, and React hooks.

outer()inner()remembered state
Runtime Visualizer

Interactive Closure Visualizer

Call the returned inner function and watch it keep access to count after outer() has already completed.

Closure code
1function outer() {
2 let count = 0;
3
4 return function inner() {
5 count++;
6 return count;
7 };
8}
9
10const counter = outer();
11
12counter();
13counter();
14counter();
Scope chain and memory

Global Scope

scope
outer: function
counter: inner()

outer Scope

scope
count: preserved in closure memory

Animated memory box

0

inner Scope

scope
count++
return count

outer() finished, but counter still points to inner(). Because inner() references count, JavaScript keeps that lexical environment alive.

Interactive Quiz

Check Your Closure Model

Test lexical scope, persistent state, memory risk, and React closure behavior.

What is a Closure?

Why does count persist?

Can closures cause memory leaks?

How do React hooks use closures?

Common Interview Questions

Closures Interview Prep

Detailed answers for the closure questions that show up in frontend and full-stack interviews.

Q1

What is Closure?

A closure is created when a function keeps access to variables from its outer lexical scope after that outer function has finished executing. The function carries its surrounding environment with it.

Q2

What is Lexical Scope?

Lexical scope means variable access is determined by where functions are written in the source code. Inner functions can read variables from parent scopes because of their placement in the code.

Q3

How do Closures work?

When an inner function references outer variables, JavaScript preserves the referenced lexical environment. If the inner function is returned or stored, that environment remains alive for future calls.

Q4

Can Closures cause memory leaks?

Yes. If a closure is kept alive by an event listener, cache, timer, or global reference, anything it references may stay in memory. Clean up listeners and avoid capturing large unused objects.

Q5

How are Closures used in React?

React callbacks, effects, memoized functions, and custom hooks all use closures. They capture props, state, and helper functions from the render where they were created, which is why dependency arrays matter.