20
loading...
This website collects cookies to deliver better user experience
const string = "hello closure";
function print() {
console.log(string);
}
hello closure
function closure() {
let counter = 0;
function onlyExecutesOnce() {
if(counter == 1) {
return;
}
counter += 1;
console.log(counter);
}
return onlyExecutesOnce;
}
/* testing the function */
const myFunction = closure();
myFunction();
myFunction();
myFunction();
1
myFunction()
is sharing the same surrounding environment as onlyExecutesOnce()
?onlyExecutesOnce()
is also attached with information of its surrounding which is being passed to myFunction()
.