Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self invoking function is undefined

If I declare a function literal:

var x = function(){
        alert('hi');
    };
    console.log(x); // returns the function code.

However:

var x = (function(){
    alert('hi');
})();

console.log(x); // returns undefined?

I don't understand why this happens. Isn't the point of writing a function as a literal is to still be able to access it by its variable reference name? I know this may be silly but I'm just learning javascript so don't judge too harshly.

like image 463
user1019031 Avatar asked Dec 12 '22 01:12

user1019031


1 Answers

Your function does not return anything, so its return value is undefined.

A self-executing function is executed and the function is not stored anywhere - only its return value survives (and any external variables the function sets/modifies).

For example, this code would be equivalent to var x = 'hi';:

var x = (function(){
    return 'hi';
})();

The purpose of self-invoking functions is usually to create a new scope, e.g. when creating callback functions in a loop:

for(var i = 0; i < 5; i++) {
    window.setTimeout(function(){ alert('i = ' + i); }, 1000 * i);
}

This would use the same i in all callbacks so it would alert i = 5 5 times.

for(var i = 0; i < 5; i++) {
    (function(i) {
        window.setTimeout(function(){ alert('i = ' + i); }, 1000 * i);
    })(i);
}

By using a self-executing function we create a new scope and thus a new i in each loop.

Another use of self-executing functions is to create a new scope where certain variables are ensured to 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);
like image 102
ThiefMaster Avatar answered Dec 24 '22 13:12

ThiefMaster