duck degen
duck degen

Reputation: 1223

function wrapped in parens

Why does this return a syntax error:

function(foo){console.log(foo)}

I'd expect this to return the value of the function, hence return itself, and not assign it to anything, but i get a "SyntaxError: Unexpected token ("

but this works:

(function(foo){console.log(foo)}) 

Please explain what purpose those wrapping parenthesis serve. I've been told that parens are used to "increase readability" but in this case there definitely is more purpose served.

Can you please go into further detail about use about () ? Say you were to translate that line of code to prose, what would the () read like? I am trying as well to describe this concept to other people, and need to transmit its meaning so that everybody can understand it. The question i'm trying to answer, is what do the ()'s mean? Do they have a semantic value, and what is it?

Upvotes: 3

Views: 298

Answers (2)

James Allardice
James Allardice

Reputation: 165971

Your first example is a function declaration. It doesn't have an identifier, which is a syntax error. Here's the grammar for a function declaration (notice that Identifier is not optional):

FunctionDeclaration :

function Identifier ( FormalParameterListopt ) { FunctionBody }

By wrapping it in parentheses you turn it into a function expression (an anonymous one). You could execute it by adding a pair of invoking parentheses after:

(function(foo){console.log(foo)})("hello"); //Will log 'hello'

Here's the gammar for a function expression (now the identifier is optional):

FunctionExpression :

function Identifieropt ( FormalParameterListopt ) { FunctionBody }


How the parentheses turn a function declaration into a function expression

In this case, the parentheses are parsed as a "grouping operator". The grammar for the grouping operator is as follows:

PrimaryExpression :

( Expression )

The grouping operator can only contain an expression, so your function is parsed as an expression rather than a declaration (obviously, in your exact example, the function can't be a declaration since it doesn't have an identifier).

Upvotes: 7

complex857
complex857

Reputation: 20753

This is because without the (), the function(){} line is a function declaration, while with the () is an expression.

function declarations are a strange beasts, they made available everywhere in the scope they are defined in before code execution, so snippets like this works:

foo();
function foo() { console.log('foo'); }

Upvotes: 2

Related Questions