In JavaScript, a closure is a feature that allows a function to access variables defined in its outer lexical scope even after that function has finished executing.
In other words, a closure is formed when a function is defined inside another function, and the inner function can access the outer function’s variables, even when the outer function has completed its execution.
function outerFunction() {
let outerVariable = 'I am outside!';
function innerFunction() {
console.log(outerVariable);
}
return innerFunction;
}
const innerFunc = outerFunction();
innerFunc(); // Output: "I am outside!"
In this example, the innerFunction
is defined inside outerFunction
, which creates a closure. innerFunction
has access to the outerVariable
even after outerFunction
has completed execution, because of the closure. When innerFunc()
is called, it logs the value of outerVariable
to the console.
Closures are a powerful feature in JavaScript that allows for more advanced programming techniques, such as creating private variables and encapsulating data.
In JavaScript, there is no built-in way to create private variables and functions within an object. However, using closures, you can achieve this behavior by creating a function that returns an object with methods that have access to private variables.
function counter() {
let count = 0;
return {
increment() {
count++;
},
decrement() {
count--;
},
getCount() {
return count;
}
};
}
const myCounter = counter();
myCounter.increment();
myCounter.increment();
console.log(myCounter.getCount()); // Output: 2
In this example, counter
is a function that creates an object with three methods: increment
, decrement
, and getCount
. The count
variable is defined inside the counter
function, making it a private variable that is inaccessible from outside the function.
The increment
and decrement
methods both modify the count
variable, while getCount
returns the current value of count
. Because the increment
, decrement
, and getCount
methods are defined inside the counter
function, they have access to the count
variable through a closure.