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:
- Closes over a boolean flag (like
hasRun) - Closes over a variable to store the result
- Checks the flag on each call
- Only executes the wrapped function if the flag is
false - Sets the flag to
trueafter 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.