16

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.

Adam Azad
  • 11,171
  • 5
  • 29
  • 70
justGoscha
  • 24,085
  • 15
  • 50
  • 61
  • Agree, FF too is right on the need for a function name with a clear cut error message - SyntaxError: function statement requires a name – hazardous Dec 17 '15 at 12:09
  • maybe because you can't do `function(){}()` (if not used as argument) but you can do `(function(){})()` – Hacketo Dec 17 '15 at 12:10
  • The first is undefined function syntax but the second is an object – SaidbakR Dec 17 '15 at 12:12

2 Answers2

28

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.

Marius Schulz
  • 15,976
  • 12
  • 63
  • 97
9

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.