My team doesn\'t have any experienced JS developers, but we are writing a library in Node and got a suggestion from a real JS developer that \"We should make the js more mod
The reason to maybe sometimes do this is because if you don't, then any variables you need for the module.exports object have to be scoped to the entire file.
Consider these two ways.
Without IIFE.
var foo = 'la' + 'la'; // some computed value
//
// ... lots of program code here ...
//
module.exports = {
foo : foo,
};
With IIFE.
//
// ... lots of program code here ...
//
module.exports = (function () {
var foo = 'la' + 'la'; // some computed value
return {
foo : foo
}
}());
In the first example, two problems arise.
foo) are created quite far away from where they are used to export a value from the module. This can reduce clarity. Sure, you can declare a variable after the program code, but it still has the same scope (and vars are hoisted). Plus, general best practice is to declare all your variables up front, and not doing so is a tradeoff to consider.The second example eliminates these problems by having a private scope for that area of the file. You can still use variables that are scoped to the entire file, but in cases where you don't need that, you can have variables that are easier to read and understand.
Often times we program for humans, not machines. This is an example of optimizing for the former.
Update:
In modern versions of JavaScript, const and let are probably better solutions to the problems this pattern aims to solve. With them, you can define variables in a way that will throw errors if you make the same mistakes the IIFE is trying to protect you from.
//
// ... lots of program code here ...
//
const foo = 'la' + 'la'; // some computed value
module.exports = {
foo : foo,
};
In the above example, if the program code uses foo, it will crash with a ReferenceError, because of the Temporal Dead Zone, as opposed to receiving undefined as a var would. This is great because now you must explicitly move the declaration of foo to an earlier place in the code if its use was intentional, or otherwise fix the code.