0

Lately, as I started to get deeper in javascript I came across some scripts where the code is inside an IIFE like:

(function(){
    // SOME CODE
})();

I know this is just an anonymus function that gets invoked after it's definition. But why is this better than just write the code without the IIFE? Or we just write the code inside this function so local variables can't be seen outside?

  • One purpose is what you've mentioned. It can be used to keep variables/functions out of the global scope. – gen_Eric Jan 06 '16 at 18:38
  • You've got it. The main point is to prevent your identifiers from being globally visible (and mutable), thus ensuring that your code will play nice with other code: you won't overwrite its state, and it can't overwrite yours. – Jordan Gray Jan 06 '16 at 18:44

1 Answers1

0

Apart from what you said it also keeps your code from polluting the global scope, making anything within the IIFE inaccessible globally. This can help modularize your code.

lackeyjb
  • 156
  • 4