Skip to curriculum
Jump to the editor

6.3. Run a function only once

Easy
Topics

This question is in

6. Functions and closures
10–15 min

Some work must happen once however many times the code asks for it: loading a script, setting up analytics, sending "first visit" to a server, initializing a shared connection. A click handler that sets something up fires on every click, so it needs a guard. once turns any function into one that runs a single time.

Write once(fn) in once.js. It returns a new function. The first call of that function runs fn and returns what fn returned. Every call after that returns the same result again, without running fn.

Signature

JAVASCRIPT
function once(fn) // returns a function
  • fn: the function to run once.
  • The returned function takes any arguments and returns fn's first result.

Requirements

  1. once returns a new function and does not call fn itself.
  2. The first call runs fn with every argument of that call and the this of that call, and returns fn's result.
  3. Later calls do not run fn; they return the first result, whatever their own arguments are.
  4. The first result is kept even when it is undefined, 0, "", false or null, and an object result is the same object every time.
  5. Each function made by once has its own state.
  6. If the first call throws, the error reaches the caller and fn never runs again; later calls return undefined.
  7. If fn calls the wrapped function while it is still running, fn does not run a second time.
  8. once does not change fn.

Examples

JAVASCRIPT
const setup = once((name) => {
  console.log("setting up", name);
  return 42;
});

setup("a"); // logs "setting up a", returns 42
setup("b"); // returns 42, logs nothing
JAVASCRIPT
const user = {
  name: "Ana",
  greet: once(function () { return "Hi " + this.name; }),
};
user.greet(); // "Hi Ana"
JAVASCRIPT
const check = once(() => 0);
check(); // 0
check(); // 0, and fn ran only once

Environment

  • Plain JavaScript in a browser page; the tests call the global once from once.js.
  • fn is always a function.
  • Out of scope: resetting the function, running it n times (problem 6.5), and async functions (a returned promise is just a result).

Hints

  1. How do you tell "not called yet" from "called, and the result was undefined"?
  2. Which kind of function receives the caller's this: an arrow function or a regular one?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…