Reputation: 16506
In reading about javascript functions, I understand that you can call a function immediately after defining it thusly:
al = function(string){
alert(string)
}("test");
but that you cannot do the same thing with empty parens:
al = function(){
alert("test")
}();
and that, instead, you have to convert the function into a function expression:
al = (function(){
alert("test")
})();
Why is this, and why does the first code example work correctly without this conversion?
Upvotes: 1
Views: 255
Reputation: 191749
All three of your examples are more or less identical. Note that the al =
does nothing functionally because none of these functions return anything, so al
will be undefined
. If they did return something, it would be assigned to al
. al =
is necessary for the first two expressions to be syntactically correct.
The first example is different in that it takes an argument. The other two don't, but that has no effect on how the expression works.
The parentheses can also be used to signal an expression. For example, (function () {})()
is valid syntax, but function () {}()
is not. =
also signals an expression, so variableName = function () {}()
also works.
Upvotes: 2