Closure in JavaScript

Closure in JavaScript

Closure is an important concept in JavaScript. I recently revised about closure, and thought of writing about same in this short article.

Before Closure lets quickly understand what Scope and Lexical Scope is.

Scope

In simple words Scope defines where a variable can be accessed and where it can't.

function f(){
    let i = 0
    console.log(i)  // => 0
}
f()
console.log(i)  // => ReferenceError: i is not defined

Here, variable i can't be accessed outside function f() as it is outside its scope therefore we get ReferenceError.

Lexical Scope

The accessibility of variable is determined by the position of the variables inside the nested scopes. i.e We can access variable from outer scope in inner scope.

function outer(){
    let i = 0
    console.log(i)  // => 0

    fuction inner(){
        let j = 1
        console.log(i) // => 0
        console.log(j) // => 1
    }
    inner()
}
outer()

Here variable i is not defined in function inner() so it will look for i in its lexical scope (function inside which inner is called i.e outer() ) and return that value to console. Because inner() is invoked inside outer(), it is called in its lexical scope itself and hence can access i.

Closure

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

function outer(){
    let i = 0
    console.log(i)  // => 0

    fuction inner(){
        console.log(i) // => 0
    }

    return inner
}

const newFun = outer()

newFun()

Here even though inner() is evoked outside of its lexical scope, it can still access variable i because it remembers( closes over) the variable i from its lexical scope. So we can say that Closure captures variables from lexical scope and remembers it so that they can be used from wherever the function is called.

It can be used in object data privacy, in event handlers and callback functions, higher-order functions, and in partial applications, currying e.t.c.

You can read more about closure on MDN web docs.

Did you find this article valuable?

Support Shweta Kale by becoming a sponsor. Any amount is appreciated!