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.

3
  • Agree, FF too is right on the need for a function name with a clear cut error message - SyntaxError: function statement requires a name Commented Dec 17, 2015 at 12:09
  • maybe because you can't do function(){}() (if not used as argument) but you can do (function(){})() Commented Dec 17, 2015 at 12:10
  • The first is undefined function syntax but the second is an object Commented Dec 17, 2015 at 12:12

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Please notice that the canonical term is function declaration. "function statement" did mean something special pre-ES6.
@Bergi Of course, thanks. Corrected!
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.