I've been using the following to begin filling out code for an IIFE:
(function() {
/* code goes here */
}());
On occasions I see the following being used:
(function() {
/* code goes here */
})();
Which is the correct one?
I've been using the following to begin filling out code for an IIFE:
(function() {
/* code goes here */
}());
On occasions I see the following being used:
(function() {
/* code goes here */
})();
Which is the correct one?
According to Douglas Crockford (the creator of jslint) the first one is less error prone when another developer reads your code. But not everyone has to respect this, both are fine though it is good to know what exists, and why.
When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.
var collection = (function () { var keys = [], values = []; return { get: function (key) { var at = keys.indexOf(key); if (at >= 0) { return values[at]; } }, set: function (key, value) { var at = keys.indexOf(key); if (at < 0) { at = keys.length; } keys[at] = key; values[at] = value; }, remove: function (key) { var at = keys.indexOf(key); if (at >= 0) { keys.splice(at, 1); values.splice(at, 1); } } }; }());
Its purely an aesthetic preference. Use whatcha like. Douglas Crockford tried real hard to popularize the first, but I more often see the second.