What do you call these patterns? What is the difference between them? When would you use each? Are there any other similar patterns?
(function() {
    console.log(this);  // window
})();
(function x() {
    console.log(this);  // window
})();
var y = (function() {
    console.log(this);  // window
})();
var z = function() {
    console.log(this);  // window
}();
EDIT: I just found two more seemingly redundant ways to do this by naming the functions in the last two cases...
var a = (function foo() {
    console.log(this);  // window
})();
var b = function bar() {
    console.log(this);
}();
EDIT2: Here is another pattern provided below by @GraceShao which makes the function accessible outside the function scope.
(x = function () {
    console.log(this);  // window
    console.log(x);     // function x() {}
})();
console.log(x);         // function x() {}
// I played with this as well 
// by naming the inside function 
// and got the following:
(foo = function bar() {
    console.log(this);  // window
    console.log(foo);   // function bar() {}
    console.log(bar);   // function bar() {}
})();
console.log(foo);       // function bar() {}
console.log(bar);       // undefined
                Here are your functions again with some comments describing when/why they might be useful:
(function() {
    // Create a new scope to avoid exposing 
    // variables that don't need to be
    // This function is executed once immediately
})();
(function fact(i) {
    // This named immediately invoked function 
    // is a nice way to start off recursion
    return i <= 1 ? 1 : i*fact(i - 1);
})(10);
var y = (function() {
    // Same as the first one, but the return value 
    // of this function is assigned to y
    return "y's value";
})();
var z = function() {
    /* This is the exact same thing as above 
     (except it is assigned to z instead of y, of course).
     The parenthesis in the above example don't do anything
     since this is already an expression
    */
}();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With