- Published on
Closure In Javascript
- Authors

- Name
- Md Abdul Momin
- @mominriyadh786
A closure is a mechanism in JavaScript where an inner function has access to variables in its outer (enclosing) function's scope, even after the outer function has finished executing. This allows the inner function to remember and access variables from the environment in which it was created, preserving the state of those variables.
Consider the following example:
function outerFunc(outerParam) {
const outerVar = 'I am outside!';
function innerFunc(innerParam) {
const innerVar = 'I am inside!';
console.log(outerParam, outerVar, innerParam, innerVar);
}
return innerFunc;
}
const myInnerFunc = outerFunc('Hello');
myInnerFunc('World');
In this code:
outerFuncis defined, taking a parameterouterParam.- Inside
outerFunc, a variableouterVaris defined. - An inner function
innerFuncis defined, which has access to bothouterParamandouterVarfrom its outer scope. outerFuncreturnsinnerFunc, creating a closure that captures the variablesouterParamandouterVar.myInnerFuncis assigned the returned closure.- When
myInnerFuncis called with the argument 'World', it can still access the values ofouterParamandouterVarfrom its outer scope, even thoughouterFunchas finished executing.
Output
Hello I am outside! World I am inside!
In this example, innerFunc forms a closure, allowing it to access outerParam and outerVar from its outer scope, even after outerFunc has completed execution. This behavior is possible because the closure "closes over" the variables from its outer scope, preserving their values for future use.
Closures are widely used in JavaScript for various purposes, such as data privacy, event handling, and creating private methods and variables in object-oriented programming.
