Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does function(){} not work, but (function(){}) does? (Chrome DevTools/Node) [duplicate]

Tags:

javascript

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.

like image 678
JustGoscha Avatar asked Dec 17 '15 12:12

JustGoscha


2 Answers

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.

like image 82
Marius Schulz Avatar answered Nov 20 '22 14:11

Marius Schulz


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.

like image 9
Michal Paszkiewicz Avatar answered Nov 20 '22 13:11

Michal Paszkiewicz