Self-invoking Functions

Anonymous functions can be used as callbacks. Same way we can make anonymous function—calling this function right after it was defined.

Below is an example.

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

The syntax is simple by adding an anonymous function definition inside parentheses followed by another set of parentheses. The second set basically says "execute now" and also you can put any parameters that your anonymous function might accept.

snippet
(function(name) {
        alert('Hello ' + name + '!');
    }
)('dude')

The advantage for using self-invoking anonymous functions is to have some work done without creating global variables.

Note
You cannot execute the same function twice (unless you put it inside a loop or another function). This makes the anonymous self-invoking functions best suited for one-off or initialization tasks.
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents