-1

Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
What is the difference between a function expression vs declaration in Javascript?

What is the right way to declare Javascript Function?

From codeacademy.com i got this way:

var someFunction = function(paramA, paramB){
    // do some function here
}

But because my basic of programming is PHP, i prefer declare function with this way:

function someFunction(paramA, paramB){
    // do some function
}

What I'm concern is which one is recommended way to declare function, I'm afraid if my preferred way have some consequences, but i love that way so much because it make my NetBeans Code Navigator can read all of my functions.

Netbeans Code Navigator

Community
  • 1
  • 1
GusDeCooL
  • 5,639
  • 17
  • 68
  • 102

1 Answers1

2

Both are acceptable. Indeed, you can also do:

foo = function bar() { 
          console.log(arguments.callee.name); 
};

If you then call foo(), you'll see "bar" in the console.

The first method creates an anonymous function and assigns it to a variable.

The second method creates a named function and places it within the current scope.

The third method creates a named function and assigns it to a variable. However, this time, the name only exists within the scope of that function.

Declaring a function with a name (function name () {}) has the advantage that you can then call the function more easily from inside itself, as may be necessary for implementing a recursive algorithm. If you don't, you have to use arguments.callee.name in order to call a function within itself, but that is warned against in MDN.

All of that is a long-winded way of saying that either is acceptable and, if in doubt, you can't go much wrong with using named functions.

Dancrumb
  • 26,597
  • 10
  • 74
  • 130