Search code examples
javascriptiife

Immediately Invoked Function Expression (IIFE) use case in Javascript


I get that IIFE's are used to prevent polluting the global name space. What I do not understand is that assuming that you have a variable that shares the same name, if you were to declare a variable using the key word var inside of a given function, wouldn't it not matter when the function was invoked at run time? I'm probably making it sound more complicated than it is but look at the code blocks below:

Example 1: Without IIFE

var firstName = "eugene";

function name(){
  var firstName = "bobby";
  console.log(firstName); 
}
name(); //bobby

console.log(firstName); //eugene

Example 2: Using IIFE

var firstName = "eugene";

(function(){
  var firstName = "bobby";
  console.log(firstName);
})();

console.log(firstName);

Example 2 outputs essentially the same thing. What is the point of using IIFE's if it's going to out put the same thing?


Solution

  • The point of the IIFE, which could (should - although the name doesn't hurt) also have been written as

    (function () {
    //       ^ anonymous
      var firstName = "bobby";
      console.log(firstName);
    })();
    

    is to not introduce the name in the global scope. In your first example, you could have invoked name() twice or as often as you wanted.