Your function returns nothing, so its return value is undefined
.
The self-executing function is executed and the function is not saved anywhere - only its return value is saved (and any external variables that the function sets / modifies).
For example, this code would be equivalent to var x = 'hi';
:
var x = (function(){ return 'hi'; })();
The goal of self-starting functions is usually to create a new scope, for example. when creating callback functions in a loop:
for(var i = 0; i < 5; i++) { window.setTimeout(function(){ alert('i = ' + i); }, 1000 * i); }
This will use the same i
in all callbacks so that it alerts i = 5
5 times.
for(var i = 0; i < 5; i++) { (function(i) { window.setTimeout(function(){ alert('i = ' + i); }, 1000 * i); })(i); }
Using the self-execution function, we create a new region and, therefore, a new i
in each cycle.
Another use of self-executing functions is to create a new area in which certain variables will be available and set to the correct value:
(function($, window, undefined) { // here the following always applies: // $ === jQuery // window === the global object [assuming the function was executed in the global scope] // undefined is well, undefined - in some js engines someone could have redefined it })(jQuery, this);
source share