Tag Archives: anonymous function

What are anonymous self-invoking functions in JavaScript?

Have you ever been confused by something like this?

(function() { 
    console.log('hello world');
})();

This function invokes itself after it has been declared, meaning it calls itself right after you have declared it. All we are doing is wrapping the function into parentheses and then call it like you would call any function with (). Think of it this way:

(function)();

Some people use .call() (which does exactly the same), because the other syntax can be confusing for people who have just started with JavaScript:

(function).call();

To finish this post off, let us have a look at a real world example of an anonymous, self-invoking function:

var list = (function() {
    // declare variables that cannot be used outside of the function scope
    var x = 10;
    var y = 20;

    return [x, y];
})();

// correctly logs [10, 20]
console.log(list);

// throws a reference error
console.log(x);