I had this code :
function (i)
{
alert(i);
}(3);
And it wasn’t working , So After StackOverFlow Question – I changed it to :
(function(i){ alert(i); })(3);
And it works.
I had to () wrap all the code.
But then I saw this code on other site :
function addLinks () {
for (var i=0, link; i<5; i++) {
link = document.createElement("a");
link.innerHTML = "Link " + i;
link.onclick = function (num) {
return function () {
alert(num);
};
}(i); // <=== What about this ? there is no () wrapper... so how does it work ?
document.body.appendChild(link);
}
}
window.onload = addLinks;
I wanted to ask what is the role for the (i) part ? Is it executing something ?
And if it Does why Its not in a pattern of :
(function(i){ alert(i); })(3);
I mean where is the wrappers of () ?
The compiler needs to differentiate between function declaration statement and function definition expression. You can only call functions in expressions.
When the keyword function appears after ‘=‘ or ‘(‘ the compiler knows this must be a function definition expression (since only expressions and not statements are allowed after ‘=’ or ‘(‘) and allows you to call it immediately. When the keyword function starts a new statement the compiler assumes it to be a function declaration statement and hence you can’t call the function immediately.
Note that function declaration statement requires you to name the function. This allows you to call it later. You may omit the function name in function definition expressions (and you can call them immediately).
Edited
all the bold fonts were made by Royi Namir the OP: those bold words are the key for understanding.
See This
http://jsbin.com/imetan/edit#javascript,html