Your product could be here, in front of thousands of JavaScript developers. Sponsor this spot →
JavaScript Quiz

How do you write a once() function with a closure?

Do you know what will be the output of this code?

JavaScript
function once(fn) {
  let done = false;
  return (...args) => {
    if (done) return;
    done = true;
    return fn(...args);
  };
}

const hello = once(() => "hi");
console.log(hello(), hello());
Show answer and explanation

The answer is hi undefined.

The returned function closes over done. The first call flips it to true and runs fn. The second call returns early with undefined.

Take the full quiz Next question →

More Closures questions

  1. How does a closure counter work in JavaScript?
  2. Why does var in a loop with setTimeout print 3 3 3?
  3. Why does let in a for loop fix the setTimeout closure problem?
  4. Do two closures from the same function share state?
  5. Does a JavaScript closure capture the value or the variable?

Related topics