DEV Community

loading...

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

Collapse
hugo__df profile image
Hugo Di Francesco

The one place where IIFEs can still be useful is surprisingly async/await in Node.

You can't use await outside of async so you end up doing something like:

(async () => {
  try {
    await something()
  } catch(e) {
    console.error(e.stack)
    process.exit(1)
  }
})()

That's unless you have top-level await support in your environment (which Node doesn't but the esm package can be configured to provide or if you transpile)

Collapse
somedood profile image
Basti Ortiz (Some Dood)

Oh, yeah. How could I forget about that?

Also, just a side note, I just realized now that top-level await is essentially a glorified way of writing top-level synchronous code. That's kind of strange... 🤔

Collapse
citguy profile image
Ryan Johnson

You could argue that the following syntax is subjectively easier to grok, because it's explicit about the definition and execution of the async function main. However, there's no technical advantage of one syntax vs the other.

async function main () {
  try {
    await something()
  } catch (e) {
    console.error(e.stack)
    process.exit(1)
  }
}

main()
Forem Open with the Forem app