Hacker News new | ask | show | jobs
by maxloh 608 days ago
What is the reason behind wrapping code inside an IIFE (Immediately Invoked Function Expression)?

JavaScript modules are scoped, so nothing can be accessed outside unless explicitly exported.

FYI, you don't even need an IIFE. ES modules are block-scoped by default.

  // Instead of,
  let foo
  (function() {
    const bar = 1
    foo = bar
  })()
  // `bar` is out of scope here

  // You can just,
  let foo
  {
    const bar = 1
    foo = bar
  }
  // `bar` is out of scope here too
1 comments

I guess history reasons