DEV Community

Discussion on: ELI5: Why use a function declaration, expression, or an IIFE in JavaScript?

 
sebvercammen profile image
Sébastien Vercammen • Edited

That's because it's an anti-pattern. This is not a valid use case.

  1. An interpreter already executes code, so you don't need to wrap it in a function. Remove the function, and you've got the same output.
  2. If you need to repeat execution, you should define a function with a descriptive name.
  3. In this case, the result will always be the same, and the whole function can be replaced with its output to save on execution time.

An IIFE is still common. It's often used in browser
content extensions or snippets loaded from providers (analytics, ads, ...), because the browser's scope is shared by all active snippets, so we limit the scope.

Thread Thread
 
somedood profile image
Basti Ortiz

Well, there's that, too. 😅