Take the 2-minute tour ×

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

share|improve this question

marked as duplicate by VisioN, Diodeus, Anthony Grist, bfavaretto, Ian Jan 22 '13 at 15:29


Technically, only the second one is a declaration. See the duplicate suggested by Diodeus. –  bfavaretto Jan 22 '13 at 15:25

1 Answer 1

up vote 2 down vote accepted

Both are acceptable. Indeed, you can also do:

foo = function bar() { 

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.

share|improve this answer
