1

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?

Ali Mamedov
  • 5,116
  • 3
  • 33
  • 47
Ahmed-Anas
  • 5,471
  • 9
  • 50
  • 72
  • Encapsulation. Function has it's own scope not visible from the outside. – Georgy May 31 '16 at 13:16
  • Generally its a good practice to avoid polluting the global scope and have all references within the scope of the function – Vijaykrish93 May 31 '16 at 13:17
  • Possible duplicate of [What is the (function() { } )() construct in JavaScript?](http://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript) – Matt Lishman May 31 '16 at 13:28

1 Answers1

3

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:

Ali Mamedov
  • 5,116
  • 3
  • 33
  • 47