BeginnerCoder

Lesson 17 — Closures

Functions that remember

A closure is a function that keeps access to the variables of the place where it was created — even after that outer function has finished. Each call to makeCounter() creates a fresh, private c.

function makeGreeter(name) {
  return () => "Hi, " + name;   // remembers name
}
makeGreeter("Sam")();   // "Hi, Sam"

++c adds 1 and gives back the new value.

Why it matters: closures give you private state without classes — they are behind counters, event handlers and React hooks.

Want it another way?
Task

Make makeCounter return a function that adds 1 to c and returns it. Two counters must count separately.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with JavaScript Foundations

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.