Self-start function 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 do not understand why this is happening. Is it not a matter of writing a function as a literal, but of still having access to it by its name, references to variables? I know this might be stupid, but I'm just learning javascript, so don't judge too hard.

+4
source share
2 answers

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); 
+8
source

If you:

 var foo = somefunction; 

... then you assign the function foo .

If you:

 var foo = somefunction(); 

... then you assign the return value of the function call to foo

Your function:

 function(){ alert('hi'); } 

... does not have a return , so it will return undefined .

+5
source

Source: https://habr.com/ru/post/1415191/


All Articles