IIFE Immediately Invoked Function Expression - jellyfish-tom/TIL GitHub Wiki

[SOURCES]

Immediately Invoked Function Expression

(function() {
    var name = 'wes';
})();

An IIFE function runs itself immediately, and it creates a scope where nothing is going to leak into the parent scope. In our case, nothing is going to leak into the global scope of the window.

If I needed to access our function’s name, obviously, I’d have to do a console.log inside of the IIFE function, but the important thing is that it’s no longer leaking into the global scope.

var funcs = [];

function createfunc(i) {
  return function() {
    console.log("My value: " + i);
  };
}

for (var i = 0; i < 3; i++) {
  funcs[i] = createfunc(i);
}

for (var j = 0; j < 3; j++) {
  // and now let's run each one to see
  funcs[j]();
}

With let and const variables, we don’t need a function for our variables to be scoped to that.

Why? Because let and const use block scope.

So with ES6+ it is better idea to use let/const