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?

mikesigs
  • 10,491
  • 3
  • 33
  • 40
  • 1
    possible duplicate of [var functionName = function() {} vs function functionName() {}](http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) – zamnuts Jun 30 '14 at 06:41
  • 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: http://stackoverflow.com/questions/3887408/javascript-function-declaration-and-evaluation-order – slebetman Jun 30 '14 at 06: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. – mikesigs Jun 30 '14 at 15:18

1 Answers1

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.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • 1
    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 Jun 30 '14 at 15:21
  • @mikesigs Using declarations is the convention. However they should be declared before they are used, not relying on hoisting. – Bergi Feb 15 '17 at 18:53