In previous articles I’ve written the topics have included the idea of JavaScript closures before (although I never explicitly said that), and I thought that I would take this opportunity to break down closures a little bit and explain some more about them.
What is closure?
According to MDN, “A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.”
To simplify this, basically, a closure is a set of nested functions where the inner function has access to variables from the outer function, even after the outer function has been executed. Let’s take a look at an example, to help visualize things…