DEV Community

Ayush
Ayush

Posted on • Edited on

Closures In JavaScript

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
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

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.

That's it for this blog!!

I hope you learnt something from my Blog!

Thank you!! 😁

Top comments (0)