JavaScript — Closures and Immediate functions

Gerard Sans
Sons of JavaScript
Published in
1 min readNov 28, 2014

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

--

--

Gerard Sans
Sons of JavaScript

Helping Devs to succeed #AI #web3 / ex @AWSCloud / Just be AWSome / MC Speaker Trainer Community Leader @web3_london / @ReactEurope @ReactiveConf @ngcruise