Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to use IIFE with ES6 modules?

In the airbnb style guide it states that IIFE are mostly never needed.

https://github.com/airbnb/javascript/blob/master/README.md#functions

7.2 Wrap immediately invoked function expressions in parentheses. eslint: wrap-iife

Why? An immediately invoked function expression is a single unit - wrapping both it, and its invocation parens, in parens, cleanly expresses this. Note that in a world with modules everywhere, you almost never need an IIFE.

// immediately-invoked function expression (IIFE)
(function () {
  console.log('Welcome to the Internet. Please follow me.');
}());

Can someone explain why this would be the case? I cannot find an explanation anywhere that says if I create a function at the top level in a module js script it would not be in the global namespace.

like image 912
richgkav Avatar asked Nov 14 '25 23:11

richgkav


1 Answers

The most common use of an IIFE is to create a scope for variables to exist in so they don't become globals.

A module has its own scope, and a variable declared in the top level of a module is scoped to that module and not globally.

like image 70
Quentin Avatar answered Nov 17 '25 13:11

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!