JS Built-ins
Closuresbeginner

Closures β€” Basic counter

πŸ“– Usage Example
function makeCounter() {
  let n = 0
  return () => ++n
}
const counter = makeCounter()
counter()  // β†’ 1
counter()  // β†’ 2

The counter closure keeps its own private count variable, so each call increments independently without any global state.

Creating a Simple Counter with Closures

A closure is a function that has access to variables from its outer scope even after the outer function has returned.

Challenge: Create a makeCounter function that returns a function. Each time the returned function is called, it should increment and return a counter starting from 1.

Example:

const counter = makeCounter()
counter() // 1
counter() // 2
counter() // 3
πŸ’‘ Hints (2)
  • β€’ Use a variable outside the returned function to store state
  • β€’ Each call to makeCounter should create a new independent counter