How do JavaScript closures work
Closures in JavaScript is a feature where an inner function has access to the outer function’s variables. In many programming languages, the variables in scope are limited to global variables, parameters, and local variables. In languages which support closures , such as JavaScript, variables may also be bound dependent on the context in which a function was declared.JavaScript closure has three scope:
- Access to its own scope, i.e., the variable defined within its curly braces.
- Access to the variables of the outer functions.
- Access to the global variables.
const countDown = (function () {
let counter = 5;
return function () {
counter -= 1;
console.log(counter);
return counter
}
})();
countDown();
countDown();
countDown();
countDown();
Output:
4
3
2
1
In the above code, the variable "countDown" is assigned to the return value of a self-invoking function. The self-invoking function only runs once. It sets the counter to five (5), and returns a function expression . This way "countDown" becomes a function. The interesting part is that it can access the counter in the parent scope. This is called a JavaScript closure . It makes it possible for a function to have "private" variables. The counter is protected by the scope of the anonymous function, and can only be changed using the countDown function.

JavaScript closures make code more compact, readable and beautiful and promote functional reuse. It has many useful applications, such as currying, simulating private data , and greatly reducing the need for global variables.
Related Topics
- JavaScript Popup Boxes
- Opening a new window in JavaScript
- How to Create Drop-Down Lists in JavaScript
- How do I include a JavaScript file in another JavaScript file?
- Print the content of a Div using JavaScript/jQuery
- How to get the current URL using JavaScript ?
- How to Detect a Mobile Device with JavaScript/jQuery
- How to validate an email address in JavaScript
- JavaScript Array Iteration
- How to Remove a Specific Item from an Array in JavaScript
- How To Remove a Property from a JavaScript Object
- How to get selected value from Dropdown list in JavaScript
- How do I get the current date in JavaScript?
- How to Open URL in New Tab | JavaScript
- How to delay/wait/Sleep in code execution | JavaScript
- How to round to at most 2 decimal places | JavaScript
- How to convert string to boolean | JavaScript
- How to check undefined in JavaScript?
- How To Copy to Clipboard | JavaScript
- How to encode a URL using JavaScript?
- How to force Input field to enter numbers only | JavaScript
- How to create multiline string in JavaScript
- How to Check for an Empty String in JavaScript?