Understanding Closures in JavaScript
It’s actually a lot simpler than what other tutorials are trying to tell you
JavaScript closure is one of those topics that can be hard to wrap your head around, simply because of how it’s often explained. Most tutorials just tell you that it’s a function within a function — but in reality, there is deeper meaning behind it all.
“Writing in ECMAScript language without understanding closure is like writing Java without understanding classes” — Douglas Crockford, father of JSON
Lets look at the code below:
However, the above code is not very efficient. It uses a global scope and there is nothing to protect it against change.
A lot of people often forget that JavaScript is a lexical scoping language. This means, inheritance flows inwards. A variable outside a function is available for usage within a function but not the other way around.
You can’t use a value that’s been declared inside a function outside it.