Closure In Javascript. (YjS)

The function is a first-class citizen in javascript.

When we execute the function then two things will happen.

  1. It will be pushed to the call stack.
  2. and create a new execution context to run that function.

In the execution context, we got following

  1. This — Object this
  2. Args — Argument array we got in functions
  3. Variable environment — Where function variables are stored and after the function execution completes, it will be popped from the call stack and those variables will be available for the garbage collector.

function create() {
cont bigData = new Array(7000);
return function(index){
return bigData[index];
}
}

Here inner function accesses the variables from the outer function even the outer function is out of the stack. The variable bigData should have to be available for the garbage collector but it is not, because of closure.

In javascript, everywhere we are using closure like in callbacks, promises, curry functions, etc.

A closure is a combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). — MDN

We can say it as a function with lexical scope (The scope where the function is declared or defined )

It simply likes functions with a backpack of accessible variables.

Advantages (comment if you want to know more about advantages)

  1. Memory efficient
  2. Abstraction

#yjs #firstblog #javascript #closure #interviewQuestion

JavaScript Developer