Closures in JavaScript

A closure is a function having access to the parent scope, even after the parent function has closed.

ยท
February 23, 2023
โ€ขโ€ขโ€ข views
Hey I am glad you are here! Today in this Blog We will be learning about Closures in JavaScript.

Basic Definition of Closure

A function along with its lexical scope bundled together is called a closure

So what do we mean by lexical scope ๐Ÿค” lexical scope means the place where the variable or functions is created

Chatting is okay lets chat with code ๐Ÿ˜

function x() {
    var a=10 // local variable 
    function y() {
      console.log(a)
    }
    return y;
}
x() // 10

In the above code we have a function x within that we have another function y. Function x creates local variable and function y prints it to console.

Function y doesn't have any local variable of its own but it has the access to local variable of its parent function x because of the Closure concept in JavaScript.

function x() {
    
    function y() {
      console.log(a)
    }
    var a=10 // local variable 
    a++;
    return y;
}
x() // 11 

Numerous Output questions can be formed on the basis of Closures concept.

To understand Closures properly we need to understand Execution Context first.

Functions run inside a Execution Context

What is execution context ? Its an abstract concept used by ECMAScript to track runtime evaluation of code.

Back to Closures

Every function creates an execution context. Execution Context comprises of comprises of variables in the function they were created and reference to the parent's environment. Since execution context got reference to its parent environment. All the variables of parent functions gets available to the inner function. This is a closure.

A closure is created every time an enclosing outer function is called. In other words, the inner function does not need to return for a closure to be created.

That's it for this blog!!

I hope you learnt something from my Blog!

Thank you!! ๐Ÿ˜

Built with TypeScript, Tailwind and Next.js โ™ฅ