Immeditaly invoked functions, as the name says, are functions that automatically self execute themselves right after their declaration, without the need of an outer call.

Why use IIFE?

In Javascript, everything that is declared out of a function is added to the global scope. In other words, a new execution context will exist only if a function is invoked.

In the example below, note that though the variable foo was declared inside a loop, your value is still accessible outside because it was assigned to the global scope window .

Notwithstanding, this arbitary pollution of the global context is undoubtedly one of the most common mistakes made by javascript developers, but it can be easily solved using IIFE or the variable declaration let , available from ECMAScript 6.

Arguments

Like any other function, an IIFE can also receive arguments. The most common use, as demonstrated in the example below, is to pass a variable for it to be used locally with an alias:

In that case, the global instance jQuery is passed through the argument $

Conclusion

Isn’t it easy? :) The article’s main goal was to summarize how IIFE works, so I’ve done my descriptions as short as possible. If you have any further questions, please, don’t hesitate to drop a comment. I’d really appreciate to answer you!

Thank y’all!