I've seen this odd behavior right now that I could not define
function(){}
or
function(a){
console.log(a)
}
It throws an Uncaught SyntaxError
.
But test = function(){}
or (function(){})
did work.
The Safari dev tools have a better error report: It says
SyntaxError: Function statements must have a name.
Okay it makes no sense to define a function like that if you will never use it. But it's still odd. I guess I have already provided the answer in the question.
JavaScript has function declarations and function expressions. The former cannot be immediately invoked, while the latter can. It's a matter of the language grammar.
Function declaration:
function foo() {
// ...
}
Function expression (on the right-hand side of the =
):
var foo = function() {
// ...
};
By adding parentheses around the function, you're forcing the function to be parsed as a function expression because it's not possible to put a function declaration within parentheses (where only expressions are expected and accepted):
(function foo() {
// ...
});
You can then immediately invoke it:
(function foo() {
// ...
})();
For a more detailed write-up, check out Function Definitions in JavaScript.
The brackets in (function(){})
mean that the function evaluates, the object is now contained inside the brackets, and this evaluation returns the function. It can be called, like this: (function(){})();
.
function(){}
does not evaluate. It makes sense for this to cause an error, because as you said, you will not be able to use it in any way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With