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?

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: stackoverflow.com/questions/3887408/… Commented Jun 30, 2014 at 6:54
  • 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. Commented Jun 30, 2014 at 15:18

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@mikesigs Using declarations is the convention. However they should be declared before they are used, not relying on hoisting.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.