2

Consider the following two examples:

First:

var x = (function(){  return 786;  }());

Second:

var y = function(){  return 786;  }();

I know that we can't use function(){ return 786; }(); directly as an anoomymus self calling function but now since I am assigining it to variable x I can use this function. So,

  • Is there any difference in result of the behaviour of variable x in First and Second method?
user31782
  • 7,087
  • 14
  • 68
  • 143
  • 2
    None, there's no difference. It's the same as `var x = (786);` and `var x = 786;`. Grouping the values between parenthesys will return the **last** value. Example: `var x = (5, function(){ return 786; }());` will set `x = 786`. – Ismael Miguel Nov 08 '16 at 13:43
  • @IsmaelMiguel But then why does javascript allow `(function(){ return 786; }());` but not `function(){ return 786; }();`? – user31782 Nov 08 '16 at 13:48
  • It does... If you run it, both do exactly the same. This is exactly the same as `var x = [786][0];` and `var x = {x: 786}.x;`, in terms of final result and (in some way) syntax. Same as `var x = {x: function(){ return 786; }}.x();` or `var x = {x: function(){ return 786; }()}.x;`. – Ismael Miguel Nov 08 '16 at 13:53
  • @IsmaelMiguel Do you mean to say we can use `function(){ return 786; }()` wherever an expression is expected for example `(//some expression)` – user31782 Nov 08 '16 at 14:05
  • Yes. That's, in a very resumed form and (possibly slightly) innacurate way. I haven't found an example where it can't be used. But, doesn't mean there isn't. – Ismael Miguel Nov 08 '16 at 14:09

1 Answers1

2

No. There wouldn't be any difference.

Wrapping the function in parentheses converts them from a function declaration to an expression and it is ok for a valid expression to be run on its own.

var x = (function(){  return 786;  }());

Here, the anonymous function wrapped in parentheses is an expression which executes the function and return 786, assigning it to the var x. Since the anonymous function is a valid expression, it can be run separately also.

var y = function(){  return 786;  }();

Here, the complete statement is an assignment expression and thus, it is executed and stores the value 786 to var y.

For further reading, check out the following links:

/questions/3384504/location-of-parenthesis-for-auto-executing-anonymous-javascript-functions

http://kangax.github.io/nfe/#function-statements

Community
  • 1
  • 1
n4m31ess_c0d3r
  • 3,028
  • 5
  • 26
  • 35