DEV Community

loading...

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

Collapse
somedood profile image
Basti Ortiz (Some Dood)

This is definitely a valid use case for it. I guess the only problem you'll ever face with this approach is readability. At first glance, it isn't really a design pattern you see often. Moreover, the algorithm isn't as straightforward as one may think. Perhaps sprinkling a few comments here and there explaining your rationale and thought processes will help. Other than that, I see nothing wrong with this. 🙂

Thread Thread
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 (Some Dood)

Well, there's that, too. 😅

Forem Open with the Forem app