DEV Community

Cover image for Closures
Prayush Adhikari
Prayush Adhikari

Posted on • Updated on

Closures

Hey! ever heard of closures in javascript?
Though it is a simple concept but very difficult to grasp. At first we have a term called lexical scope.

1.Lecical Scope: It means that the location of any variables is dependent on the scope where it is located. Functions create their own scope. Lets take a look at an example to understand the concept more properly.

let globalVariable = "This is global Variable"
function test()
{
    let innerVariable="This is inner variable"
    console.log(globalVariable)
    console.log(innerVariable)
}

test()

console.log(globalVariable)
console.log(innerVariable) //Throws an error!
Enter fullscreen mode Exit fullscreen mode

Running the code will make you clear about the scopes of variable is limited within a function. Since the innerVariable scope is within the test() function's enclosure it cannot be accessed from outside the enclosure.

2.Closure: A closure is created when an inner function is defined within the body of an outer function and has access to variables in the outer function's scope chain, even after the outer function has returned.

Lets take an example of the a closure:
function outerFunction() {

function outerFunction(){
let outerVariable = 'I am outer';

function innerFunction() {

  console.log(outerVariable);
  }

  return innerFunction;
}

const myInnerFunction = outerFunction();

myInnerFunction();
Enter fullscreen mode Exit fullscreen mode

The output of the program will be

I am outer
Enter fullscreen mode Exit fullscreen mode

Since after returning the outerFunction the outerVariable should be inaccessible but due to the closure the innerFunction can access the outerVariable.

Top comments (0)