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?
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.
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.
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?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With