Hone

Lessons · TypeScript · functions that remember

A function that remembers where it was made

A function keeps access to the variables around it when it was created, even after the outer function has returned.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Event handlers, counters, debounce, React hooks, private state: closures are the mechanism under most front-end code.

How to think about it

Does this function need memory between calls? When you need a function with memory, make it inside another function that holds the state. Each call to the outer function makes a fresh, independent memory.

Worked example

function once(fn) {
Wrap any function so it runs at most once.
  let done = false, result;
Private memory: nothing outside can touch it.
  return (...args) => {
The inner function remembers done and result.
    if (!done) { done = true; result = fn(...args); }
First call runs fn and remembers.
    return result;
Later calls return the remembered value.
  };
}
const init = once(() => console.log("setup") || 42);
init() logs once; every call returns 42.

Your turn

Make a greeter that remembers its name.

function greeter(name) {
  return () => `hi ${}`;
}

The trap

A loop with var creating handlers that all see the final value. Use let in the loop, or a closure per iteration.

Practise functions that remember on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.