Search code examples
javascriptjqueryiife

Why do JQuery uses IIFE (Immediately invoked function expression)


I got an explanation that so it won't pollute the global variable environment. But why not just declare normal function and call it at the end?

function$(){ some awesome code here with variables declared with var keyword}
$();

Solution

  • When you create a function like:

    function doSomething() {
        ...
    }
    

    It is created under window, and it is accessible as window.doSomething. So even if the variables inside the function do not spill outside, the function name itself pollutes the global namespace. Thus it may potentially conflict with the custom functions developer may wish to use.

    Instead, when you use IIFE, and expose the functions under jQuery or $, the global namespace remains clear.