You can implement functions like once using closures!
it uses the concept of scope, or "backpack".
Basically when you have a function that also returns a function, that returned function gets the variables and data around it (accessible to it in the same scope) in its "backpack", or more officially, in its [[scope]] hidden/private property!
That allows us to do pretty cool stuff, like for example, create an implementation of the 'once' function!
const creator = (cb) => {
let counter = 0;
function once() {
if(counter >= 1) {
console.log("Function only runs once!");
}
else {
counter++;
console.log(cb());
}
}
return once;
}
const callback = (a, b) => {
return a+b;
}
const newOnce = creator(() => callback(1, 6));
newOnce();
newOnce();
let's explain what this code does:
-
Here we have a closure called creator, it takes a callback, that does whatever we want, here however, it simply adds two numbers together.
const creator = (cb) => {
-
then we define a counter variable to track the number of times we ran the code
let counter = 0;
-
We check the value of counter if it exceeds 1, then we don't execute the callback code, otherwise, we go ahead with the execution
function once() { if(counter >= 1) { console.log("Function only runs once!"); } else { counter++; console.log(cb()); } }
-
we finally return the function
return once;
One of the coolest things here is that the memory is permanent! the function returned from the closure remembers its previous state, which is really powerful!
I learned this feature recently when I was studying js and closures, and thought it would be cool to try and explain it, hope it would be useful to someone.
Cheers!
Top comments (0)