Created
February 16, 2024 16:11
-
-
Save flyptkarsh/46a95a25d9ad60fd0f34447cee3ee415 to your computer and use it in GitHub Desktop.
Counter Closure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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