Do you know what will be the output of this code?
JavaScript
function once(fn) {
let done = false;
return (...args) => {
if (done) return;
done = true;
return fn(...args);
};
}
const hello = once(() => "hi");
console.log(hello(), hello());
Show answer and explanation
The answer is hi undefined.
The returned function closes over done. The first call flips it to true and runs fn. The second call returns early with undefined.