JS Function

https://www.w3schools.com/js/js_function_closures.asp
https://www.w3schools.com/js/tryit.asp?filename=tryjs_function_closures5

On a topic on this first page, the counter example is processed, there is an issue that my mind cannot solve. In Javascript, when the local functions finish their task, don’t the variables and everything declared inside are not deleted, how can it remember the previous variable or data when the event is called (button clicked) again?

Hi @Muhammed_Koc and welcome to the community :wave:

I completely understand your confusion. It’s a hard topic to wrap one’s mind around.
The most important sentence on your linked page is the last one:

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

This sounds rather counterintuitive but is true. Even when the outer function has stopped running, its scope still exists and another function that was created inside (and was returned) still has access to this scope.

MDN has a long articles about JavaScript closures with a lot of examples. If you are interested in this topic I absolutely recommend reading it.

Have a nice day! :slightly_smiling_face:
Michael

Thanks for your answer. Also, I didn’t think my question would be answered so quickly. So, is this feature specific only to javascript language, or does it have this feature in other languages?

1 Like

Glad it helped!

That’s an interesting question I never thought about. I found the Wikipedia article about closures. After skimming through it I think the general rule is: If a language allows to pass functions as parameters and to return them (first-class functions), then they probably support closures. Such languages are for example Lisp, Rust or Python.