javascriptiife

What does this javascript code mean?


var myval = (function(){})();

I don't understand (function..) meaning and even else code.


Solution

  • What you've got there is a:

    self-invoking anonymous function

    You're first creating a function-expression by having paranthesis around the function itself. Just to write

    function() {
    }()
    

    would not work in this instance, because this would define a function-declaration.

    So after we have that, we can call itself by appending ()

    (function() {
    })();
    

    To verify that, try this:

    var myval = (function(){return 'self executed!'})();
    
    alert(myval); // === 'self executed'