JavaScript Function Closures
Listen to this article
A global variable in the global scope can also be used in a local scope. This means expressions in a local scope can reach out to variables in a global scope.
See the example below:
const name = 'Bello'; // global variable
const outerFunc = () => {
console.log(`My name is ${name}.`);
// global variable in a local scope
}
const outer = outerFunc();
outer; // My name is Bello. => global variable
Below is another example:
const outerFunc = () => {
const scope1 = "outer scope";
const innerFunc = () => {
console.log(scope1);
}
console.log(innerFunc());
}
const outer = outerFunc();
outer; // global variable
With closure, a global variable can be made local (private).
See the example below:
const outerFunc = () => {
const scope1 = "outer scope";
const innerFunc = () => {
console.log(scope1);
}
return innerFunc;
}
const outer = outerFunc();
outer; // [Function: innerFunc] => private global variable
Closure makes the
innerFunc()
have access to theouterFunc
, but theouterFunc()
has no access to theinnerFunc
.
outerFunc()()
calls both theinnerFunc()
andouterFunc()
.
// outerFunc()();
const outer = outerFunc();
outer(); // outer scope
Happy coding
No Comments Yet