Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
6.3. Run a function only once
Easy
Topics
This question is in
6. Functions and closuresSome 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
function once(fn) // returns a functionfn: the function to run once.- The returned function takes any arguments and returns
fn's first result.
Requirements
oncereturns a new function and does not callfnitself.- The first call runs
fnwith every argument of that call and thethisof that call, and returnsfn's result. - Later calls do not run
fn; they return the first result, whatever their own arguments are. - The first result is kept even when it is
undefined,0,"",falseornull, and an object result is the same object every time. - Each function made by
oncehas its own state. - If the first call throws, the error reaches the caller and
fnnever runs again; later calls returnundefined. - If
fncalls the wrapped function while it is still running,fndoes not run a second time. oncedoes not changefn.
Examples
const setup = once((name) => {
console.log("setting up", name);
return 42;
});
setup("a"); // logs "setting up a", returns 42
setup("b"); // returns 42, logs nothingconst user = {
name: "Ana",
greet: once(function () { return "Hi " + this.name; }),
};
user.greet(); // "Hi Ana"const check = once(() => 0);
check(); // 0
check(); // 0, and fn ran only onceEnvironment
- Plain JavaScript in a browser page; the tests call the global
oncefromonce.js. fnis 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
- How do you tell "not called yet" from "called, and the result was
undefined"? - 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…