5

Possible Duplicate:
Javascript: var functionName = function() {} vs function functionName() {}

What is the reason you would do:

somename = function(param1, param2) { }

In stead of doing:

function somename(param1, param2) { }
Community
  • 1
  • 1
PeeHaa
  • 71,436
  • 58
  • 190
  • 262

3 Answers3

3

Well since the 1st syntax is a variable declaration and the 2nd is an actual function declaration, i would stick to the 2nd unless I truly needed the 1st.

Try to read up on scoping and variable hoisting and you will see that the 2nd syntax can sometimes create trouble for you :)

http://www.dustindiaz.com/javascript-function-declaration-ambiguity/

http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

Btw, you might want to browser this thread and look for more good stuff: var functionName = function() {} vs function functionName() {}

Community
  • 1
  • 1
Martin Jespersen
  • 25,743
  • 8
  • 56
  • 68
  • I understand. However what would be a situation when you would use de declaration of a variable way? – PeeHaa Sep 22 '11 at 10:35
  • 1
    Well there are many places where you can use it, but few places where you need to. One that comes to mind, is if you use a 3rd party framework/library and have to overload an existing function in the library/framework. – Martin Jespersen Sep 22 '11 at 10:43
1
$fn = function(param1, param2)

By using the above form you are able to pass $fn to any function as a parameter, or you could create a new object from that:

function doSomethingWithFn($fn);

or

$fnObject = new $fn(param1, param2)

You can use the second form when you just need a utility function, or for closures:

function utilityFn(str) {
    return str.indexOf('a')
}
var str = utilityFn('abc');

or

$('#element').click(function() {
    utiliyFn($('#element').html())
})
Vlad Balmos
  • 3,372
  • 19
  • 34
0

The first method creates a function object that you can then pass as parameter to other functions. For example, if you want to execute some code when a text box value changes, you can set a callback like this (using jQuery):

var onChange = function() { /* ... */ }
$("#username").change(onChange);
npclaudiu
  • 2,401
  • 1
  • 18
  • 19