JS Built-ins
Closuresintermediate

Closures β€” Execute function once

πŸ“– Usage Example
function once(fn) {
  let called = false, result
  return (...args) => {
    if (!called) { called = true; result = fn(...args) }
    return result
  }
}
const init = once(() => 'initialized')
init()  // β†’ 'initialized'
init()  // β†’ 'initialized' (fn not called again)

Closures preserve flags and cached results across calls, making it easy to execute a function only once and reuse its result.

Function That Executes Only Once

Create a wrapper that ensures a function is called at most once, ignoring subsequent calls.

Challenge: Create a once(fn) function that returns a wrapper. The first time the wrapper is called, it executes fn and caches the result. All subsequent calls return the cached result without executing fn again.

Example:

let n = 0
const increment = () => ++n
const onceIncrement = once(increment)
onceIncrement() // 1, n becomes 1
onceIncrement() // 1, n stays 1
onceIncrement() // 1, n stays 1
πŸ’‘ Hints (3)
  • β€’ Use a flag to track whether the function has been called
  • β€’ Store the result in a closure variable
  • β€’ Return the cached result on subsequent calls