1

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?

Eug
  • 165
  • 1
  • 2
  • 11
  • There are many examples of this question already on stack. http://stackoverflow.com/questions/14317998/immediately-invoked-function-expression-iife-vs-not – SoEzPz Apr 04 '17 at 22:18
  • possible duplicate of [Difference between a named IIFE and calling a name function immediately?](http://stackoverflow.com/q/15688420/1048572) – Bergi Apr 04 '17 at 22:22
  • it's... just a function that gets called immedaitely. Why does it need to have a point? it do what it do. – Kevin B Apr 04 '17 at 22:32
  • @SoEzPz I've taken a look at your suggestion and a whole lot of other questions similar to this. It still didn't answer my question. That's why I asked. – Eug Apr 04 '17 at 22:42

2 Answers2

1

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.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
-1

If the function is non IIFE you must call the function , if it a IIFE function no need to the call the function It executes immediately after it’s created.