Ahmed-Anas
Ahmed-Anas

Reputation: 5619

javascript: reason for declaring and immedieatly calling inline function

So I had an interview where I was asking the purpose of declaring and calling a function immideately, and i couldn't answer it, i.e:

(function(){

    // code
})();

What's the reason for doing this?

Upvotes: 1

Views: 67

Answers (1)

Ali Mamedov
Ali Mamedov

Reputation: 5256

Object-Oriented JavaScript - Second Edition: One good application of immediate (self-invoking) anonymous functions is when you want to have some work done without creating extra global variables. A drawback, of course, is that you cannot execute the same function twice. This makes immediate functions best suited for one-off or initialization tasks.

The syntax may look a little scary at first, but all you do is simply place a function expression inside parentheses followed by another set of parentheses. The second set says "execute now" and is also the place to put any arguments that your anonymous function might accept:

(function() {

})();

or

(function() {

}());

are the same:

Upvotes: 3

Related Questions