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?
1 Answer 1
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.
functionsignals a function declaration, and not a function-call expression that starts with an anonymous function.al =from either the 1st or 2nd example will create a declaration, which cannot be followed by calling parenthesis. Stripping it from the 3rd, the extra parenthesis still make it an expression.