The reason
function() { return val;} ();
doesn't work is because it's a function statement, not an expression. It's a pretty minor distinction, but basically, if the statement starts with function
, it's just like a C function declaration, and you can't call the function, because there is no expression value.
Adding the parentheses makes the function definition part of an expression, so it has a value and can be called.
Assigning the return value of the function also eliminates the need for parentheses, because the function definition is not the whole statement. For example, these work:
var value = function() { alert("works"); return 0; }();
(function() { alert("works"); })();
but this doesn't:
function() { alert("doesn't work"); }();
I always include the parentheses, even when they aren't necessary because it makes it easier to see that I'm calling the function, instead of assigning it to a variable.