Search code examples
javascriptiife

Benefits of wrapping code inside an IIFE in JavaScript


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?


Solution

  • 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.