Skip to content

Instantly share code, notes, and snippets.

@flyptkarsh
Created February 16, 2024 16:11
Show Gist options
  • Select an option

  • Save flyptkarsh/46a95a25d9ad60fd0f34447cee3ee415 to your computer and use it in GitHub Desktop.

Select an option

Save flyptkarsh/46a95a25d9ad60fd0f34447cee3ee415 to your computer and use it in GitHub Desktop.
Counter Closure
function counter() {
// This variable is private to the counter function
let count = 0;
// The function returned is a closure that
// has access to the count variable
return function() {
count += 1; // Increment the count
return count; // Return the updated count
};
}
// Create an instance of the counter
const count = counter();
console.log(count()); // Logs: 1
console.log(count()); // Logs: 2
console.log(count()); // Logs: 3
// Each time count() is called,
// the count variable is incremented and its new value is returned.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment