Function Declaration vs Function Expression in the Module Pattern [duplicate]
Asked Answered
D

1

5

I have just learned about the difference between Function Declarations and Function Expressions. This got me wondering about whether or not I'm doing things right in my AngularJS code. I'm following the pattern used by John Papa, but now it seems at odds with the typical JS approach to the Module Pattern. John Papa makes heavy use of nested Function Declarations in his controllers and services. Is this bad?

Is there any reason to favor this:

var foo = (function() {
    var bar = function() { /* do stuff */ };
    return {
       bar : bar
    };
}());

foo.bar();

over this:

var foo = (function() {
    return {
       bar : bar
    };

    function bar() { /* do stuff */ };
}());

foo.bar();

I'm primarily a C# developer and still getting used to all of the nuances of JavaScript. I prefer the latter approach because all of the functions within the IIFE are private, and the revealing module pattern at the top is really the public part. In a C# class I always have my public properties and methods before the private supporting functions. However, I realize it's likely not as cut and dry in the JS world.

What are the hidden dangers (if any) of using the latter approach?

Durstin answered 30/6, 2014 at 6:24 Comment(2)
In this specific case I don't think there is any significant difference. However, read this question and the accepted answer for a full understanding of the differences: #3887908Thomasina
That's where I started actually. I read through that and a whole bunch of other great resources online, but none were really specific to IIFEs or the Module Pattern.Durstin
E
8

There is no functional difference between the two approaches, it's just stylistic.

The JavaScript interpreter will invisibly "hoist" the function declarations from the latter style to the top of the nested function anyway - if it didn't, the return block would be referencing an undefined function.

Elinorelinore answered 30/6, 2014 at 6:50 Comment(2)
That's certainly what I was hoping to hear. If it's only a matter of style, then I definitely prefer the declarative approach. However, that seems to fly in the face of popular convention.Durstin
@Durstin Using declarations is the convention. However they should be declared before they are used, not relying on hoisting.Valueless

© 2022 - 2024 — McMap. All rights reserved.