Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we need to wrap ES6 code in an IIFE?

Tags:

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?

like image 751
Vyacheslav Palamar Avatar asked May 23 '16 19:05

Vyacheslav Palamar


People also ask

Is IIFE obsolete?

With that said, an IIFE is pretty much obsolete now that we can declare block-level scopes as such. However, IIFEs are still prevalent because of backwards-compatibility.

Should I use IIFE Javascript?

An IIFE is a good way to secure the scope. You can use IIFEs to prevent global variables' definition issues, alias variables, protect private data, and avoid conflicts of using many libraries that export the same object name.


1 Answers

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?.

like image 93
Michał Perłakowski Avatar answered Oct 05 '22 05:10

Michał Perłakowski