OneCompiler

Closures in Javascript

249

In this post, I will explain about closures which is one of the concepts which is more complex to understand. I will explain to you in clear and simple code snippets.

Closure

The closure is a feature in Javascript where a function can be declared inside another function. So variables declared in outer function can be accessed in the inner function.

Scope of closure is

  • Closures has access to global variables.

  • Access to its own variable

  • Access to the outer function's variables

Let's look at an example of simple closure.


function outside() {
  var firstName = 'One';
  
  function inside() {
    var lastName = 'Compiler';
    var name = firstName + ' ' + lastName
  }
 return inside; 
}

In the above example, we declared two functions outside and inside.

The function outside has the variable firstName and returning the function inside.

The inner function inside has the variable lastName and access the outer function variable lastName.

Now let us call the outside function and store that in a variable.


function outside() {
  var firstName = 'One';
  
  function inside() {
    var lastName = 'Compiler';
    var name = firstName + ' ' + lastName
    console.log(name);
  }
 return inside; 
}

var a = outside();

a();

Let's see what will be the output of above code by step by step

  • First outside() function will be invoked and variable firstName will be initialized to **One **.

  • In the next line function inside() is declare nothing will execute.

  • At last there is a return statement which is returning function inside. Here function will not be executed the entire body of function will be returned.

  • Actually once the function is executed the variables declared inside the function will no longer exist. But in inside() function it is accessing the variable which is declared in outside().

Javascript will solve this issue by using closures.

Inner function will preserve the scope of the outer function once it is executed, and thus inner function can access the variables of outside function.

Hence we will get output if we execute function by using variable a.