Skip to content
GreenSnippets

Run a function only once

Wrap a function so it executes on the first call and returns the same result afterwards.

JavaScript
function once(fn) {
  let called = false;
  let result;
  return function (...args) {
    if (!called) {
      called = true;
      result = fn.apply(this, args);
    }
    return result;
  };
}

Example / expected output

Output
const init = once(() => loadConfig());
init(); init(); // loadConfig runs once

How it works

Useful for lazy initialization, one-time setup and idempotent handlers. The result (including a returned promise) is cached, so concurrent callers share one in-flight operation.

  • JavaScript Tested

    Memoize a function

    Cache results by argument so expensive pure functions only run once per distinct input.

  • JavaScript Tested

    Curry a function

    Turn a multi-argument function into one that can be called a few arguments at a time.

  • JavaScript Tested

    Compose and pipe functions

    Chain single-argument functions left-to-right with pipe, or right-to-left with compose.