The common practise for creating modules is to wrap them in parens so you won't leak any variables outside of the module (when concatenating etc).
There is also void
operator, which evaluates a given expression and returns undefined
. (See on MDN)
I wonder what is the reason behind preferring wrapping functions in parens instead of using void
. Is it historical, is it something related to concatenation, else?
I know that you can have problems with concatenation when one of the files has a missing a semicolon, leading to nasty problems till you notice it.
Examples
Say, module1.js (notice the missing comma):
(function () {
return function () {
console.log('module1. I should not be called');
};
})()
and, module2.js:
(function () {
return function () {
console.log('module2. I should not be called either');
};
})();
If you concat these scripts into a bundle, it will produce this:
(function () {
return function () {
console.log('module1. I should not be called');
};
})()(function () {
return function () {
console.log('module2. I should not be called either');
};
})();
Since both modules(files) return a function, the second supposedly IIFE becomes an invocation of the return value of the first module, effectively calling console.log
. The common workaround for this is to declare your module with !(function (){})();
which forces the returned value to be a boolean.
If however, you were to use void
, like:
void function () {
return function () {
console.log('module1. I should not be called');
};
}()
The concatenated file will still be wrong, but you will notice the error on the first run, therefore more easily noticed. See below.
void function () {
return function () {
console.log('module1. I should not be called');
};
}()void function () {
return function () {
console.log('module2. I should not be called either');
};
});
This throws Unexpected token void
. As fas as the modules are concerned, I believe !(function(){}()
and void function(){}()
achieve the same effect. But I feel like void
looks more clean (subjective) than wrapping a function with params and prepending !
to it.
I am missing something? Wouldn't it be better if we used void
?
void …
,;(…)
,!…
) never took off. – Verneyvoid
?" could also be answered with "there are simpler ways to reach the same goal". – Verney