JavaScript Closure

JavaScript Closure

Closure is one of the most important concepts in JavaScript. It is widely discussed and still confused concept. I used to get confused a lot when I had started to learn code. If you are a beginner and trying to understand closures this is for you.

To understand the closures, you need to know what scope and lexical scoping is.

Scope

When we define a variable, we want it to be available but within some boundaries. It's not a good practise to define a variable where its scope is accessible globally. For example, we don't need addition variable to be available to subtract() function.

The context in which variables are accessible or can be referenced. If a variable or other expression is not "in the current scope," then it is unavailable for use. This is all managed by scope In JavaScript, a scope is created by a function or a code block.

function scopeFunction(){
     // Function Scope
     let age = 23;
     console.log(age); // --> 23
}

scopeFunction() // Calling the Function
console.log(age) // --> ReferenceError: count is not defined

In the above code example, you can see that console.log(age) inside scopeFunction() get to access the variable named age and logs out 23. If you try to access the age variable from outside of scopeFunction() scope it is inaccessible and throws error as seen in the code above. Variables can be accessed only inside the code block or function. But the opposite is not true.

Treat this like a game. You have completed the level 1 with above example. Let's get to level 2.

function outerFunction() {
    // the outer scope
    let outerVar = 'Let me in!';

    function innerFunction() {
      // the inner scope
      console.log(outerVar); // --> logs "Let me in!"
  }
    innerFunction();
}
outerFunction();

Now what's happening in the above code example is outerFunction() contains innerFunction() inside its code block. Since outerVar and innerFunction() lies in the same scope. It has access to its variables. This is known as nested functions. Where a function contains another function in its code block. Note that functions are the first-class citizens in JavaScript, therefore, you can return a function from another function.

With this you have completed level 2. Until now you have learned about function scope and that scope can be nested.

Lexical Scoping

Since we are already familiar with scope, lexical scoping will be easy to understand. Lexical scoping defines the scope of a variable by the position of that variable declared in the source code. For example:

let name = 'Satyam';

function greeting() { 
    let message = 'Hi';
    console.log(message + ' '+ name); // --> "Hi Satyam"
}
greeting();

In the above example:

The variable name is a global variable. It is accessible from anywhere including within the greeting() function. The variable message is a local variable that is accessible only within the greeting() function. If you try to access the message variable outside the greeting() function, you will get an error.

In simpler terms, an item's lexical scope is the place in which the item got created. So the lexical scope of variable name and message is global scope and greeting() scope respectively. Lexical scope has nothing to do with where the variable is invoked(call into use) but where it is defined.

We seem to be doing good and have completed level 3. Let's dive to the final level and complete this game of closures.

Closure

According to MDN, A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

Gathering all the knowledge we have by completing the 3 levels we can say that - In JavaScript, closure provides access to the outer scope of a function from inside the inner function, even after the outer function has closed. JavaScript closure helps in the data privacy of the program as well. This was a fun game with 4 levels and covered many topics. We will learn more about data privacy in the future.

Thanks for reading this. If you liked this article please react, comment and follow me here and on twitter.