0

When defining a closure (or module pattern) I've seen some developers use either a function expression e.g. var f = function{...}; or use a function declaration function f {...}.

I understand hoisting and the general differences, but I'm concerned about any differences that might apply in a closure.

I'm wondering which is preferred and why? Any advantages/disadvantages? If there are no general differences which is more common?

Consider the two styles below:

var deepThought = (function(){

    var someSecret = "42";

    function whatIsTheAnswerToTheUltimateQuestion() {
        return someSecret;
    }

    function whatIsTheUltimateQuestion() {
        return "I'm not sure yet. You might have to wait a while...";
    }

    return {
        whatIsTheAnswerToTheUltimateQuestion : whatIsTheAnswerToTheUltimateQuestion,
        whatIsTheUltimateQuestion : whatIsTheUltimateQuestion
    };

})();

var deepThought2 = (function(){

    var someSecret = "41";

    var whatIsTheAnswerToTheUltimateQuestion = function () {
        return someSecret;
    };

    var whatIsTheUltimateQuestion = function () {
        return "I'm not sure yet. You might have to wait a while...";
    };

    return {
        whatIsTheAnswerToTheUltimateQuestion : whatIsTheAnswerToTheUltimateQuestion,
        whatIsTheUltimateQuestion : whatIsTheUltimateQuestion
    };

})();
gmetzker
  • 515
  • 1
  • 8
  • 21
  • As far as the module pattern is concerned, both styles are identical. – Ja͢ck May 29 '13 at 04:35
  • This is not really a duplicate. I'm specifically asking about differences or preferences when it comes to a closure / module pattern. – gmetzker May 29 '13 at 04:38
  • It's not a closure, it's an anonymous function – zerkms May 29 '13 at 04:38
  • See this question http://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname – Arun May 29 '13 at 04:39
  • Well, yes it's an anonymous function, but with a closure. Maybe the proper terminology is module pattern? – gmetzker May 29 '13 at 04:41
  • 1
    @gmetzker - while the *question* may be slightly different, the three first answers (when sorted by points) in that linked answer discuss the pros and cons of each method and discuss in some detail the differences between them - which is, if I understand your question correctly *exactly* what you are looking for. – Sean Vieira May 29 '13 at 04:42
  • The wrapping function (which isn't, of itself, a closure, if I understand it correctly) doesn't make any difference in this case - it just provides a one more level of scope for the interpreter to search. – Sean Vieira May 29 '13 at 04:43

0 Answers0