2

What is the significance of, wrapping the entire content of a JavaScript source file in a function block?

dpk45
  • 107
  • 2
  • 12

1 Answers1

3

It is common practice to wrap browser JavaScript in an IIFE in order to keep variables private and not pollute the global scope.

Global variables are generally considered bad. They encourage error-prone patterns and make it more difficult to reason about your programs.

Node.js has a nifty trick up its sleeve where it actually wraps your module in a function automagically on your behalf. As a result, you will almost never see anyone wrap their Node.js code in an IIFE. Though you may still see it used inline to scope a small chunk of code.

Thanks to ES6 and block scoping we can actually avoid the slight overhead of an IIFE by using a block statement instead.

{
    const foo = 1;
    // ... code that you would put in an IIFE ...
    // ... but do NOT use `var` ...
}
console.log(foo);  // ReferenceError: foo is not defined

Further reading: https://www.sitepoint.com/joys-block-scoping-es6/

Seth Holladay
  • 8,951
  • 3
  • 34
  • 43