Back to Interview Prep
Course progress0/14 chapters · 0%

Chapter 5 of 34

~10 min

Scope & Closures

Scope determines where a variable is visible, and closures are what let a function "remember" the scope it was created in - even after that outer function has finished running. This is one of the ideas that trips people up most, so it is worth sitting with a real example.

Global, Function, and Block Scope

A variable declared outside any function is in the global scope and accessible everywhere. A variable declared with `var` inside a function is scoped to that whole function. A variable declared with `let`/`const` inside a `{ }` - even just an `if` block or a loop - is scoped only to that block.

This is called lexical scoping: a variable's scope is determined by where it is written in the code, not where the function is called from.

What a Closure Actually Is

A closure happens whenever an inner function references a variable from an outer function's scope. Even after the outer function returns, the inner function keeps access to that variable - it is not garbage collected, because the closure is still "closing over" it.

The classic example is a counter factory: a function that returns another function which increments and remembers a private count.

Try it yourself

<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>

Output

The Closure-in-a-Loop Gotcha

A common bug: using `var` in a loop that schedules callbacks (like `setTimeout`), expecting each callback to see the loop's current value - but since `var` is function-scoped, every callback shares the same single variable, and by the time they run, the loop has finished. Switching to `let` fixes this, because `let` creates a fresh binding for each iteration.

Try it yourself

<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>

Output

Coding challenge

Write a createGreeter(name) function that returns a function which, when called, logs "Hello again, <name>!". Create a greeter for "Priya" and call the returned function twice.

<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>

Output

Answer every question below to mark this chapter as complete.

Quiz Yourself

Score: 0/4

1. What determines a variable's scope in JavaScript?

2. What is a closure?

3. In the classic loop bug, why does using `var` cause every setTimeout callback to log the same final value?

4. Which scope does a `let` variable declared inside an `if` block belong to?

You're viewing a free lesson. Sign up free to track your progress and unlock the full course.Sign up freeSign in