What is Closure in JavaScript?

Closure in JavaScript is when a function is able to remember and access it’s lexical scope even when it is executed outside of it’s lexical scope.

Put another way, it’s a function which can access it’s lexical scope after the containing function has finished executing.

One use of closures is in event handler’s. You can set up a function which an event handler will trigger at a later point in time, and the lexical scope that was defined at the time you wrote the code will be remembered at that later point in time.

There could be hardcoded values in the closure, or values can be passed in at runtime. This makes them very flexible.