I had this code :
function (i)
{
alert(i);
}(3);
And it wasn\'t working , So After StackOverFlow Question - I changed it to :
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).
all the bold fonts were made by Royi Namir the OP: those bold words are the key for understanding.
this is the most logical Explanation after a lot of tests.
http://jsbin.com/imetan/edit#javascript,html
The (i)
part is passing the value of i
as parameter to the anonymous function (function without name) which is declared as the onclick
event handler, that's all. It doesn't really "do" anything.
Sorry, I stand corrected.. the (i)
is executing the function passing i
as parameter. This results in the onclick
actually being such function:
function (num) {
alert(num);
};
If you will try to access the variable i
just like this from the function you'll always end up with its final value, 5 in this case.