Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function Declaration vs Function Expression in the Module Pattern

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?

like image 603
mikesigs Avatar asked Jun 30 '14 06:06

mikesigs


1 Answers

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.

like image 125
Alnitak Avatar answered Nov 14 '22 23:11

Alnitak