Skip to content

Instantly share code, notes, and snippets.

@mtzfox
Last active July 12, 2023 06:32
Show Gist options
  • Save mtzfox/40c69a3eca0152678a8bf9ad3151327b to your computer and use it in GitHub Desktop.
Save mtzfox/40c69a3eca0152678a8bf9ad3151327b to your computer and use it in GitHub Desktop.
The closure (internal function) here allows for the counter to keep track of how many times the function has been called. - In order for it to work, the function first has to be asigned to a variable as a function expression, with that being called instead of the function directly.
function myFunc() {
let count = 0;
return function () {
if (count < 3) {
console.log(count);
count++;
} else {
console.error('maximum count has been reached');
throw 'max count';
}
};
}
@mtzfox
Copy link
Author

mtzfox commented Jul 12, 2023

Example

const instanceOfCount = myFunc();

console.log(instanceOfCount()); // 0
console.log(instanceOfCount()); // 1
console.log(instanceOfCount()); // 2
console.log(instanceOfCount()); // Error: max count // "maximum count has been reached"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment