JavaScript — Closures and Immediate functions
JavaScript always has something cool to it. Besides callbacks and anonymous functions you may find yourself in the need for closures.
Closures can adopt the form of an Immediately Invoked Function Expression (IIFE):
Or a simple function:
An interesting characteristic of closures is that they carry the scope at the time of their invocation along with them. In the following example safe_i is stored along with the calls so its value is not 5 for all iterations.
As a former C# Developer I found it quite interesting.
Buggy
Fixed
You can run the code following the link below. In order to see the console messages you need to toggle the console for your browser Developer Tools.
Demo code: Link