// Function to create a counter using closure
function createCounter() {
let count = 0;
// Closure: Inner function maintains access to the outer function's variable
return function() {
count++;
return count;
};
}
// Create a counter using the createCounter function
const counter = createCounter();
// Usage: Increment and display the counter value
console.log(counter()); // Output: 1
console.log(counter()); // Output: 2JavaScript Closure for Creating a Counter
Related Posts
More content you might like
Code
How to Create a New MySQL User with Full Privileges
No preview available for this content.
May 01, 2025
Read More Code
python
Configuring SQLAlchemy with PostgreSQL on Heroku: A Quick Guide
This code ensures that:
- If the
DATABASE_URLstarts withpostgres://(Heroku's default), it replaces it with the correct format,postgresql+psycopg2://, making the URI compatible with SQLAlchemy.
Nov 08, 2024
Read More Code
php
How to Delete All WordPress Posts and Their Uploads Using a Custom PHP Script
No preview available for this content.
Oct 25, 2024
Read More Code
php
How To enable all error debugging in PHP
No preview available for this content.
Oct 25, 2024
Read MoreDiscussion 0
Please sign in to join the discussion.
No comments yet. Be the first to share your thoughts!