2

I am pondering on the following Javascript best practice pattern. I have a function in my code that has some nested functions. which of the following patterns should be preferred and why?

function parent() {
    function child1() {
        //child 1 code
    }

    function child2() {
        //child2 code
    }
    //parent code
    return {
        child1: child1,
        child2: child2
    };
}

or

function parent() {
    var child1 = function () {
        //child 1 code
    };
    var child2 = function () {
        //child2 code
    };
    //parent code
    return {
        child1: child1,
        child2: child2
    };
}
John Dvorak
  • 24,891
  • 12
  • 64
  • 80
Shai Aharoni
  • 1,828
  • 11
  • 24
  • 1
    Do you need [code review](http://codereview.stackexchange.com/)? – FLCL Dec 23 '13 at 10:17
  • 1
    possible duplicate of [var functionName = function() {} vs function functionName() {}](http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) – Antony Dec 23 '13 at 10:18
  • 1
    @FCL This has nothing to see with codereview. – Denys Séguret Dec 23 '13 at 10:18
  • 1
    @ShaiAharoni Assigning functions to a variable makes it easier to pass them around as parameters to other function. To me, the second one is favorable for this reason. – PEIN Dec 23 '13 at 10:18
  • @dystroy, may be you are right, but am not framework class library;) – FLCL Dec 23 '13 at 10:22
  • 1
    Whoever clicked **primarily opinion-based** clearly did not read the answer. – vbence Dec 23 '13 at 11:05
  • @peim not "easier", "more obvious the same works". Still a valid reason, even if you're going to grow out of it ;-) – John Dvorak Dec 23 '13 at 11:57
  • 2
    @vbence hmm... I think the question is much better after my edit than before. Do you think the same? – John Dvorak Dec 23 '13 at 12:25
  • @JanDvorak Yep, I agree, it's clearly a better approach. :) – vbence Dec 23 '13 at 13:54

2 Answers2

5

The main difference between those two versions is that with

var a = function(){ ...

the function is undefined until this line (but the variable exists) while in

function a() { ...

the function is defined since the start of the enclosing function :

console.log(a); // logs "function a(){ return 2} "
console.log(b); // logs "undefined"
function a(){ return 2};
var b = function(){ return 2};

As Jan points out, the first version also defines the name property of the function.

Other than that, there's no difference and it's mainly a matter of style, with no best practice I know.

Denys Séguret
  • 335,116
  • 73
  • 720
  • 697
-1

All named functions in js are accessible by their names.

another suggestion would be.

var parent;

parent = function() {
  var child1, child2;
  child1 = function() {};
  child2 = function() {};
  return {
    child1: child1,
    child2: child2
  };
};
Robbie Bardijn
  • 405
  • 2
  • 6