JavaScript · Level 3 Functions

Closures in JavaScript

Keep a variable alive inside a function's scope and hand out only the functions allowed to touch it — the trick behind counters and private state.

  • Inner functions see outer variables
  • Each call creates a fresh scope
  • Returning an object of functions

A function keeps access to the variables of the scope it was created in, even after that outer function has returned. Every call builds a new scope, so each result gets its own private copy.

function makeGreeter(greeting) {
  return (name) => `${greeting}, ${name}!`;
}

const hi = makeGreeter("Hi");
hi("Ana");   // "Hi, Ana!" — greeting was remembered

Write makeCounter(start = 0) that returns { increment, value }: increment() adds 1 and returns the new count, value() returns it, e.g. makeCounter(10).increment() returns 11.

solution.js
Test Suites Pending
Output