0

I've seen two ways of writing an Immediately-Invoked Function Expression:

// A - Parentheses around 
// the function. Then 
// invocation.
var a = (function() {
  return 4 + 5;
})();

// B - Parentheses  
// around the function  
// AND the invocation.
var b = (function() {
  return 4 + 5;
}());

console.log('a: %s - b: %s', a, b);
// Result: a: 9 - b: 9

From what I can say: Both ways work.

But I'm wondering:

What is the correct way?

Or are there different situations where I have to prefer the one way over the other?

cluster1
  • 4,968
  • 6
  • 32
  • 49
  • 1
    Both. And it your case you even don't need parenthesises. `var a = function(){...}();` would work too, but will look weird – Alexey Ten Mar 04 '16 at 07:14
  • As far as I remember Crockford recommends using the second approach, although I personally prefer the first one – Max Koretskyi Mar 04 '16 at 07:15
  • 1
    And, another duplicate: [What is the difference between those self-executing anonymous function (aka IIFE) implementation](http://stackoverflow.com/questions/16026909/what-is-the-difference-between-those-self-executing-anonymous-function-aka-iife) – jfriend00 Mar 04 '16 at 07:16
  • And, another duplicate: [What are the different ways of writing an IIFE? What are their use cases?](http://stackoverflow.com/questions/33651198/what-are-the-different-ways-of-writing-an-iife-what-are-their-use-cases/33651269#33651269) – jfriend00 Mar 04 '16 at 07:21
  • @Alexey Ten - Great! Wasn't aware that is possible to call a function that way. Thanks a lot. – cluster1 Mar 04 '16 at 07:22

0 Answers0