Note - To understand closures, we first need to know what lexical scoping is.
What is Lexical Scoping?
- Lexical scoping means that a variable’s visibility is determined by where it is written in the code.
- It’s also called static scoping.
- Let’s look at a simple example:
function outer() {
const greeting = "Hello";
function inner() {
console.log(greeting);
}
inner();
}
outer(); // Output: Hello
console.log(greeting); // ReferenceError: greeting is not defined
- In this example, the
inner()
function can access thegreeting
variable fromouter()
because it is written inside theouter()
function. - This happens due to lexical scoping, where inner functions can use variables from their parent function.
What is a Closure?
- A closure is a function that remembers and uses variables from the place where it was created, even after that outer function is done running.
Here’s an example:
function outer() {
const greeting = "Hello";
return function inner() {
console.log(greeting);
};
}
const closureFunction = outer(); // This returns the inner function
closureFunction(); // Output: Hello
- Here, the
inner()
function is returned byouter()
and saved inclosureFunction
. - When we call
closureFunction()
, it still remembers thegreeting
variable fromouter()
, even thoughouter()
has already finished.