0

I'd like to know if there is any difference when defining self-executing functions in the following ways:

var f = (function(){
    return function(){
        document.getElementById("f").innerText = "Hello f";
    };
})();

var g = (function(){
    return function(){
        document.getElementById("g").innerText = "Hello g";
    };
}());

var h = function(){
    return function(){
        document.getElementById("h").innerText = "Hello h";
    };
}();

They seem to give the same result. Please see http://jsfiddle.net/sosegon/nj4ttnmu/

BR, SV

sosegon
  • 119
  • 1
  • 2
  • 10
  • 1
    They are identical. One of the first two is preferred as the opening "(" provides a hint that it's an IIFE, whereas in the last, it's not obvious until the last line. – RobG Nov 26 '15 at 01:39
  • Relevant http://kangax.github.io/nfe/ – Jared Smith Nov 26 '15 at 01:41
  • Every JS style guide I ever saw prefers the first pattern: `(function(...) {...})(...)` or `(function name(...) {...})(...)`. – Amadan Nov 26 '15 at 01:46
  • @Amadan—doesn't Crockford prefer `(...())` or perhaps you don't care for his style? I don't really care about the call, just the leading `(`. :-) Some other [*discussion*](http://nerds.airbnb.com/immediately-invoked-function-expressions-and/). – RobG Nov 26 '15 at 01:50
  • @RobG: It seems you are correct. Now every JS style guide I ever saw but one prefers the first pattern. :P – Amadan Nov 26 '15 at 01:59
  • @Amadan: Actually this is one of the few things that Crockford got right imo :-) – Bergi Nov 26 '15 at 02:04
  • Also a duplicate of [What is the difference between two declarations of module in javascript?](http://stackoverflow.com/q/15023560/1048572) – Bergi Nov 26 '15 at 02:05

0 Answers0