Closures in Javascript

Closures in Javascript

What are closures in Javascript and how it works

What is a closure?

A closure is a javascript function that can access the scope of its surrounding state (lexical environment).

Eg:

const a = "HEHEH"
function print(){
    const b = a + " Siuuuu" // a is outside the scope of the function but is still accessible
    console.log(b)
}
print()
//output : HEHEH Siuuuu

Closure encapsulates the function and its outer state which helps the inner function access the outer scope.

How does this work?

We know that a function awaits its execution in the task queue and when its time comes it gets pushed into the call stack.

The local variables of the function get pushed to stack memory. When the execution completes the function gets popped out of the call stack and so are its local variables from stack memory.

But due to Closure the outer variables get stored in heap memory and they remain there until they are garbage collected.

This helps the function access the outer variables without any fuss!

Why is this useful?

In other programming languages, similar code may throw errors but it works perfectly fine in javascript. But. what is the use?

It can be used to declare private variables

eg:

const myfunc = () => {
    const a = 10;
    return () => {
        console.log(a+10)
    }
}
const createFunc = myfunc()
createFunc()
//output : 20
const myfunc = () => {
    const a = 10;
    return () => {
        console.log(a+10)
    }
}
const createFunc = myfunc()
console.log(a)
//output : a is undefined
  1. In the first example, we see that myfunc() returns another function that has access to the variable 'a' (outside its scope), and the output upon its execution is correct.

  2. In the second example, we see that when we try to access variable 'a' outside the scope of myfunc() it throws an error.

  3. This helps us to declare private variables which are only accessible by the returned function and hence prevent any unnecessary leakage.