JS
See the Pen thecodelog.com - JS Closure 1 by Deano (@deangilewicz) on CodePen.
Above, thing() is executed outside of its declared lexical scope. Typically, we would expect the inner contents of myFn() to go away (be garbage collected) once myFn() is executed. However, closures do not let this happen. By virtue of where it was declared, thing() has a lexical scope closure over the inner scope of myFn(), which keeps that scope alive for thing() to reference at any later time. thing() still has a reference to that scope, and that reference is called closure.
See the Pen thecodelog.com - JS Block Closure 2 by Deano (@deangilewicz) on CodePen.
Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function. A closure must preserve the arguments and variables in all scopes it references. Since each call provides potentially different arguments, a new closure is created for each call to outside. The memory can be freed only when the returned value inside is no longer accessible.
See the Pen thecodelog.com - JS Block Closure 3 by Deano (@deangilewicz) on CodePen.
Below, the use of an immediately invoked function expression (IIFE) inside each iteration creates a new scope for each iteration. This gives the timeout function callbacks the opportunity to close over a new scope for each iteration that has a variable with the correct per iteration value in it to be able to access.
See the Pen thecodelog.com - JS Block Closure 4 by Deano (@deangilewicz) on CodePen.