Course contentsShow
← JavaScript
Lesson 518 of 2,72313. ClosuresFree lesson

Once Functions

Wrap functions to ensure they execute only one time by tracking invocation state in closure.

Once Functions

You'll learn how to create a function wrapper that guarantees any function executes exactly one time, no matter how many times it's called.

The Core Idea

A "once" function is a higher-order function that wraps another function and ensures it can only run once. After the first invocation, subsequent calls do nothing (or return the cached result). This pattern uses closures to track whether the function has already been executed.

Think of it like a self-destructing button: press it once and it works, but after that, pressing it again does nothing—the mechanism has already been spent.

How It Works

You create a wrapper function that:

  1. Closes over a boolean flag (like hasRun)
  2. Closes over a variable to store the result
  3. Checks the flag on each call
  4. Only executes the wrapped function if the flag is false
  5. Sets the flag to true after first execution
function once(fn) {
  let hasRun = false;
  let result;

  return function(...args) {
    if (!hasRun) {
      result = fn(...args);
      hasRun = true;
    }
    return result;
  };
}

const initializeApp = once(() => {
  console.log('App initialized!');
  return { status: 'ready' };
});

initializeApp(); // logs "App initialized!", returns { status: 'ready' }
initializeApp(); // silent, returns cached { status: 'ready' }
initializeApp(); // silent, returns cached result again

The closure captures hasRun and result, creating a permanent memory that persists across all calls to the returned function.

Key Takeaway: Once functions use closures to track invocation state, guaranteeing a wrapped function executes only on the first call—perfect for initialization routines or expensive operations that should never repeat.