Lev Lev - 1 month ago 16
Javascript Question

IIFE without parentheses around the function statement

In the following example, concerning closures, I see this:

function addButtons(numButtons) {
for (var i = 0; i < numButtons; i++) {
var button = document.createElement('input');
button.type = 'button';
button.value = 'Button ' + (i + 1);
button.onclick = function(buttonIndex) {
return function() {
alert('Button ' + (buttonIndex + 1) + ' clicked');
};
}(i);
document.body.appendChild(button);
document.body.appendChild(document.createElement('br'));
}
}

window.onload = function() { addButtons(5); };


How come the
onclick
method isn't defined as follows?:

button.onclick = (function(buttonIndex) {
return function() {
alert('Button ' + (buttonIndex + 1) + ' clicked');
};
})(i);


Doesn't an IIFE require the following syntax:
(function statement)(arguments)
?

Answer

The original code works because the IIFE appears in an assignment, and so there is no ambiguity that the right part of the assignment is indeed an expression.

Without the assignment, the parser would misunderstand it to be a function declaration, and therefore would throw a syntax error, indicating that the declared function lacks a name. In that case the parentheses are necessary to make it an IIFE.

But it is common practice to always include the parentheses for an IIFE, even when used in an assignment.