I have a worked on a couple different projects and I have seen two different ways of creating jQuery/JavaScript functions.
The first:
function testFunction(){
};
The second:
var testFunction = function (){
};
Is there a difference between these?
The main difference is the first one (a function declaration) is hoisted to the top of the scope in which it is declared, whereas the second one (a function expression) is not.
This is the reason you are able to call a function that has been declared after you call it:
You can’t do that with a function expression, since the assignment happens in-place:
There is also a third form (a named function expression):
In this case, the identifier
myFuncis only in scope inside the function, whereastestFunctionis available in whatever scope it is declared. BUT (and there’s always a but when it comes to Internet Explorer) in IE below version 9 themyFuncidentifier wrongly leaks out to the containing scope. Named function expressions are useful when you need to refer to the calling function (sincearguments.calleeis deprecated).Also note that the same is true for variable declarations:
You can imagine that the JavaScript engine interprets the code like this: