What is closure in JavaScript ?

In JavaScript, if you use the function keyword inside another function, you are creating a closure.

The following code returns a reference to a function:

The above code has a closure because the anonymous function function() { console.log(text); } is declared inside another function, sayHello2() in this example.

In C and most other common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed.

In JavaScript, if you declare a function within another function, then the local variables can remain accessible after returning from the function you called. This is demonstrated above, because we call the function say2() after we have returned from sayHello2(). Notice that the code that we call references the variable text, which was a local variable of the function sayHello2().

Leave a Reply

Your email address will not be published. Required fields are marked *