Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function declaration. When to use what? [duplicate]

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) { }
like image 532
PeeHaa Avatar asked Oct 09 '22 22:10

PeeHaa


2 Answers

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() {}

like image 173
Martin Jespersen Avatar answered Oct 12 '22 12:10

Martin Jespersen


$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())
})
like image 36
Vlad Balmos Avatar answered Oct 12 '22 13:10

Vlad Balmos