Closures are awesome and confusing
I want to share how I started to understand Closures in JavaScript.
This is a beginner friendly view with a simple example.
Closures is a function wrapped inside of a functions body that can be referenced to its scope chain e.g. outer variables.
Definition from the book Speaking JavaScript “A closure is a function plus the connection to the scope in which the function was created” -Dr.Axel Rauschmayer
So this is how it could look like
newCounter closes over increment, counter can be referenced to and accessed by increment. The Closure now holds the scope chain and prevents it from being garbage collected.
counter1 and counter2 will keep track of their own value.
This is a very simple but hopefully a clear perspective of what closures are.
There is some really good explanations out there on why closures could be used, If you have some good knowledge or resources please share below.
Enjoy your code.