Closure :
Closures in JavaScript are like small memory bubbles that remember the environment in which they are created. This means you can create a function that remembers and accesses the data from the parent function even when the parent function is no longer running. It's a way to store and use information that would normally be forgotten once a function completes its job.
In simpler terms, closures help you keep data private and organized within your function. learnmore
Example:
// example
function outerFunction(x) {
function innerFunction(y) {
return x + y;
}
return innerFunction;
}
//creating a closure by calling outer function
const closure = outerFunction(10); // pass the x parameter with value 10
// Now we can use closure to add 5 to the remembered x
const result = closure(5);
console.log(result); // result will be 15
Here's a breakdown of what's happening in the code:
outerFunction
is defined, which takes a parameterx
.Inside
outerFunction
, another functioninnerFunction
is defined, which takes a parametery
and returns the sum ofx
(from the outer scope) andy
.outerFunction
then returnsinnerFunction
.When we call
outerFunction
with10
, it returnsinnerFunction
, creating a closure wherex
is remembered as10
.we store this closure in the variable
closure
.Later, we call
closure
with5
, which adds5
to the remembered value ofx
(which is10
), resulting in15
.
Thank You For Reading