What is the significance of, wrapping the entire content of a JavaScript source file in a function block?
Asked
Active
Viewed 1,617 times
1 Answers
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
-
thanx @seth holladay – dpk45 Jan 06 '17 at 07:04
-
No problem @dpk45. And welcome to Stack Overflow. :) I am happy to provide more details if you need. Otherwise, feel free to accept the answer. – Seth Holladay Jan 06 '17 at 07:21