Do we need to wrap ES6 code in an IIFE?

Vyacheslav Palamar picture Vyacheslav Palamar · May 23, 2016 · Viewed 7.9k times · Source

In ES5, writing such code has been considered as good practice:

(function () {
    //some magic
})();

But in ES6 variables created with let keyword are not attached to window object.

So, is there any need now in writing our code in an IIFE, or it still has some purposes I haven't heard about?

Answer

Michał Perłakowski picture Michał Perłakowski · May 23, 2016

If you're using modules, there's no need to use IIFE (that's how this "wrapper" is called), because all variables have scope limited to the module.

However, there still are some cases when you want to separate one part of the code from another, and then you can use IIFE.

Of course if you're using let or const, you can use a block statement instead of IIFE:

{
  let something = 1;
  const somethingElse = 2;
}
console.log(something); // ReferenceError: something is not defined

See related question on Programmers.SE: How far should encapsulation in JavaScript go?.