0

In my javascript console surrounding a value with parenthesis doesn't change the output.

1
=> 1
(1)
=> 1

Same thing with a string variable:

x = "foo"
=> "foo"
x
=> "foo"
(x)
=> "foo"

Same thing with a function in a variable:

f = function(){}
=> function (){}
f
=> function (){}
(f)
=> function (){}

If I don't assign the function to a variable I get an error:

function(){}
=> Uncaught SyntaxError: Unexpected token ((…)

Surrounding the anonymous function with parenthesis and I get the expected result:

(function(){})
=> function (){}

Why is this?

Thanks for any insight.

Chris
  • 6,076
  • 11
  • 48
  • 62
  • 1
    Putting the function definition inside the grouping operator forces the definition to be evaluated as *function expression* (because the grouping operator can only contain an expression) as opposed to a *function declaration* (without the parens). The name is optional in function expressions but not in function declarations. It's the same as `{"foo": 42}` vs `({"foo": 42})`, i.e. forcing the parser to interpret this as an *object initializer*, not a *block*. – Felix Kling Sep 23 '15 at 15:45
  • Along with what Felix Kling mentioned, this means that wrapping the function inside `(...)` allows you to call it directly. For example: `(function(){alert("test")})()` will do `alert("test")`. – Spencer Wieczorek Sep 23 '15 at 15:49
  • See http://www-archive.mozilla.org/js/language/grammar14.html. – chepner Sep 23 '15 at 15:50

0 Answers0