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() {

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.

(function(name) {
        alert('Hello ' + name + '!');

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

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 #
Contents +