DEV Community

talent
talent

Posted on

Javascript Closures

javascript : JavaScript Interview Question for beginners !!!

What is Closure in JavaScript?

To understand closure we need to first understand scope of a function?
What is scope?
What is scope of a function?
or
we can think of scope from other side as well, Is this variable inside scope of this function?

scope -> Where I can access the specific variable in our code?

let outerVariable = 'outer'
function testScope() {
let innerVariable = 'inner';
function displayVariable() {
console.log(outerVariable);
console.log(innerVariable);
}
displayVariable();
}
testScope();

output of above code is:
outer
inner

It's very strange, innerVariable is not inside displayVariable function scope, but still I can access that variable? -> The answer is that in javascript function can access the variables defined in its parent function.

But its again a bit strange outerVariable is defined in global scope, why displayVariable function can have access to global scope? -> The answer is scope chaining. If a function can have access to its parent function scope -> than Its parent has also access to scope of its parent-> and this chain continues until the global scope.

I hope it is bit clear about scope and scope chaining.

Now I will use a term very often used to define closure -> lexical environment:

lexical environment = local memory + lexical environment of its parent

So to understand it we need to see how call stack is dealing with functions -> when execution context of function is created, a reference to its parent function scope is also created -> So as we dive deep into nested functions, this reference is created for each layer

If you understood above discussion
-> I hope its bit clear about local scope and lexical environment,
Now I will move towards closure:

Closure -> A function bind together with its lexical scope is called as closure.

In above example -> displayVariable() function forms a closure

On top of this there are many things we can do using this concept-> we can return a displayVariable() function and use it anywhere else in our code. -> you see beauty of javascript I can have access to innerVariable in above code from anywhere else in my code.

This is just very basic level explanation to help you understand meaning of closures. To understand it for sure first you need to understand following terms:

  • scope
  • lexical scope
  • execution context
  • call stack

If you want read more about the topic I will link mdn docs reference in comment section.

Top comments (1)

Collapse
 
talenttinaapi profile image
talent