JavaScript Function Closures

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

image.png


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 the outerFunc, but the outerFunc() has no access to the innerFunc.

outerFunc()() calls both the innerFunc() and outerFunc().

// outerFunc()();

const outer = outerFunc();
outer(); // outer scope

Happy coding


image.png


image.png

No Comments Yet