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
  • 69,318
  • 57
  • 185
  • 258

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
  • 24,934
  • 6
  • 54
  • 66
  • 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,322
  • 17
  • 33
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,349
  • 1
  • 16
  • 18