Simplifying Closures in JS!
Closure is a javascript function that has access to its own scope, outer function’s scope and global scope even after the outer function has completed its execution. Variables
How closure works?
When a function is defined inside another function, it forms the closure. The inner variable “closes” over the variables from the outer function meaning it remembers the variables even when it is called outside its original scope.
Uses of closure
- Data Privacy: Closures can be used to create private variables.
function createCounter() {
let count = 0; // Private variable
return {
increment: function() {
count++;
return count;
},
decrement: function() {
count--;
return count;
},
getCount: function() {
return count;
}
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.getCount()); // 2
Explanation of Private Variables
- Scope: The variable
count
is declared inside thecreateCounter
function. Because of JavaScript’s lexical scoping rules, it is only accessible withincreateCounter
and the inner functions that are returned. - Encapsulation: The inner functions (
increment
,decrement
, andgetCount
) can access and manipulatecount
, but there’s no way to accesscount
directly from outside thecreateCounter
function. This means thatcount
is effectively "private" and “protected” from outside interference, which can help prevent bugs and maintain integrity. - Controlled Access: The only way to interact with
count
is through the methods provided in the returned object. This encapsulation ensures that the internal state can only be modified through controlled means.
What can a closure store?
In JavaScript, a closure can store various types of data, as it captures the entire lexical scope in which it was created. Here’s what you can store as a closure:
1. Variables
Any variable (primitive types, objects, arrays) declared in the outer function’s scope can be accessed and modified.
Eg: count
in the above example
2. Functions
Functions can be stored in closures, allowing you to create higher-order functions or factory functions.
function greet(greeting) {
return function(name) {
return `${greeting}, ${name}!`; // Captured variable
};
}
const sayHello = greet('Hello');
console.log(sayHello('Alice')); // "Hello, Alice!"
Summary ✨
In summary, closures are a powerful feature in JavaScript that allows functions to remember their lexical scope, enabling data encapsulation and creating private variables. Closures can store any data type available in the JavaScript scope, including variables, functions, objects, and arrays. They are widely used in various programming patterns and techniques.