2

Code1:

var x=(function(){
  return {
    greet:function(){
      alert('Hello from code1');
    }
  };
})();

Code2:

var x=function(){
  return {
    greet:function(){
      alert('Hello from code2');
    }
  };
}();

Both will be invoked like:

x.greet();

In the style 1 I've enclosed the self executing function within parenthesis while in the second code it is not. Both work same. So what is the difference between code1 and code2 and which is remanded way?

Saurabh Palatkar
  • 3,242
  • 9
  • 48
  • 107
  • As a note - I had originally suggested this be closed as "primarily opinion based", but realized afterwards - while the answer might be "its an opinion", the question itself can be concretely answered. – Krease Jun 14 '16 at 01:28
  • Nope, they're different. The first one will *run* the function then assign it to `x`, but the second one will assign `function` to the `x` then run `x` function. This can be tested when the function does not `return` anything. – choz Jun 14 '16 at 01:32

2 Answers2

5

There is no practical difference. Some people prefer one way over the other, similar to the preference for putting opening braces on the same line or the next line, or tabs vs spaces, or writing x=1+2 instead of x=(1+2).

Extra parentheses can add clarity, or clutter, depending entirely on style preference.

Krease
  • 15,805
  • 8
  • 54
  • 86
2

There is minimal difference between the two examples. Both create variables from return value of immediately invoked functions. The first is wrapped in parenthesis, as an expression, the second is a function that is immediately called. See also What do parentheses surrounding a object/function/class declaration mean?

Community
  • 1
  • 1
guest271314
  • 1
  • 15
  • 104
  • 177