Skip to the solution
EasyFrontend5 min read

Implement once(func) — ensure a function runs only once

765 views

The problem

Problem, as an interviewer would state it: "Write once(fn) — it returns a new function that, no matter how many times it's called, only ever actually invokes fn the first time. Every subsequent call should return whatever the first call returned, without running fn again."

Examples:

Code
const init = once(() => { console.log("running"); return 42; });
init(); // logs "running", returns 42
init(); // does NOT log, returns 42 again

Clarifying questions expected:

  • Should later calls' arguments be used for anything, or always ignored once the function has run?
  • Does this need to be preserved if fn relies on it?
  • Should the cached result be memory-cleared eventually, or live forever with the closure?

Code / implementation expected: Yes — real, direct proof the underlying function's call count stays at 1 even after multiple invocations, and that the returned value is genuinely cached, not recomputed.

  • once
  • closure

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

5 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: once() genuinely calls the underlying function exactly one time, caches its result, and preserves this-binding — verified directly

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 30 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Polyfill Object.fromEntries() — Handle Duplicate and Symbol Keys

Continue