Lev Lev - 1 year ago 122
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');

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

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

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download