3

Sorry for the horrible title, once people give me some direction I can edit it better for the future.

I'm mainly curious as to what the difference between

(function() {
   return false; // logs false
}());

and

(function() {
   return false; // Also returns false
})();

is, they both seem to give me the same result in the console but I'm sure there must be a difference, could somebody tell me the difference and why you would use one over the other?

Datsik
  • 14,453
  • 14
  • 80
  • 121

3 Answers3

3

As in the other answer, there is no functional difference

However, if you are into ES2015, and use an arrow function style IIFE

(() => {
   return false; // logs false
})();

works, however, this version:

  (() => {
     return false; // logs false
  }());

does not - js engine complains about missing ) in parenthetical

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
1

No difference-- just two different ways of writing an IIFE (Immediately Invoked Function Expression) in Javascript. Whichever you choose is a choice of convention.

(If you need more information about IIFE's in Javascript, there's a great SO here.)

Community
  • 1
  • 1
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
0

Either of the following two patterns can be used for IIFE uses the function's execution context to create "privacy."

(function(){ /* do something */ }()); // Douglas Crockford recommends

(function(){ /* do something */ })(); // This way works as well

Why? Because the reason of the parenthesis is to differentiate between function expressions and function declarations, they can be removed when the parser already expects an expression.

when making an assignment, coding convention states using them is a good idea.

Abs
  • 3,902
  • 1
  • 31
  • 30
  • `Douglas Crockford recommends ... why` - because he thinks final `()` in `})()` look like it's hanging out there like dogs balls - seriously, his words - too bad ES2015+ requires dogs balls to work! – Jaromanda X Oct 09 '16 at 06:29
  • Yes as i mentioned convention states let them hang out..you got the point ;) – Abs Oct 09 '16 at 06:42