by
2
5
386k
4
Top 1% !
Popular
Tagged
Specified
OpenSource
Popularity: 1338th place
Created
Modified Oct 1, 2014
Languagejavascript
LicenseMIT_X11

A simple IIFE and closure example in Javascript

This snippet shows the beauty of Immediately Invoked Function Expression (IIFE) and closures in Javascript.

Here we create a function and immediately invoke it. This is also known as 'self executing function'.
With the syntax var car = (function(){...})(); we define the function and execute it at the same time.

Closure instead allows developing better modular code.
You can see the function returns an object which is stored in variable car. 
Using closure the object being returned can access the variable _name defined by the parent function.
This is helpful also for emulating private variables.

Thanks to http://www.htmlxprs.com/post/14/superpower-your-javascript-with-10-quick-tips
post this code
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/179204/A-simple-IIFE-and-closure-example-in-Jav?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
var car=(function(){ var _name='Ferrari GTO'; return { getName: function(){ return _name; } } })(); //function created and invoked console.log(car.getName()); //Ferrari GTO
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus