Skip to content
dreamcode
dreamcode
Map
Closures
Lesson 24 of 48
+15 XP on finish
JAVASCRIPT CLIMBSChapter 5 · JS Functions and Classes

Scope and closures

A closure is created when an inner function remembers variables from its outer lexical environment, even after the outer function finishes executing.

Worked example

How it reads

  • let count = 0 defines a private counter variable
  • return () => { ... } maintains lookup access to the count variable
Cloud tip: Closures allow you to create private state variables in JavaScript.
index.js
JAVASCRIPT
real JavaScript, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Write makeCounter() that returns a function adding 1 to a private count each call. Call it three times and log the last result: 3.

Press Run to check your work.