Search code examples
javascriptiife

The confusion about the way how IIFE works


I am beginner at JavaScript and faced the confusion concerning the way IIFE works in JavaScript. That is, I got that it is used basically to escape variable is assigned to a global variable to avoid collisions. But here is the thing, say, we have a code like:

var number = 7;

(function() {
  var number = 7;
  alert(number);
})();
//In this code collision does not happen due to IIFE

But what if I write:

var number = 7;

function num() {
  var number = 7;
  alert(number);
}

/*In this code there does not happen collisions and 
number variable is not assigned to the global scope as well. So, why use IIFE?*/
num();


Solution

  • An Immediately Invoked Function Expression (IIFE) has more than one use. The one that you're focusing on is that an IIFE doesn't pollute the global scope when declaring a variable within it (or any other functions/methods).

    Another important thing using an IIFE does is that it allows your code to immediately run without someone else's code interfering. Also, an IIFE runs without having to call a function by name that would presumably exist in the global scope.

    The key here is that your code is both: not interfering with things in the global scope, and is protected from outside influence since anything in the global scope could mistakenly be overwritten.

    ...you are shielding your code from someone who may change your globals accidentally, or sometimes intentionally!

    Checkout this medium article on Mastering IIFEs for more info.


    Update

    A good example of why your second example could negatively effect something is this:

    If you import a library of some kind, and it has a method named num (that the library used internally) in the global scope (because it didn't use an IIFE), your second example would overwrite that method, and make it unusable within the library.

    The key here is that it's not just scoping. The variables declared within any method are scoped to that method, not the global scope. But a named function is within the global scope.