Roy Posted March 20, 2013 Share Posted March 20, 2013 Let's see if I even got this right... From what I understand, the following creates a named function and assigns it to a variable: var someVar = function functionName() { //function body }; And this creates an anonymous function assigned to a variable: var someFunction = function() { //function body }; What I don't understand is what the functional difference is between the two, so could someone please explain this to me? Link to comment Share on other sites More sharing options...
Larry Posted March 20, 2013 Share Posted March 20, 2013 JavaScript is a bit crazy, no? Okay, so these are both function expressions (as opposed to function declarations), with one being a named function expression and the second being unnamed (aka anonymous). Normally, function expressions are anonymous, as you can refer (and invoke) the function through the variable anyway. If you do name the function, as in the first example, this gives you a second way to invoke the function: directly through its name. It can also be helpful in debugging, as the debugger can report an actual function name, not just "anonymous", depending upon the debugger in use and the situation. All in all, though, we're talking about rather trivial differences. Hope that helps! 2 Link to comment Share on other sites More sharing options...
HartleySan Posted March 20, 2013 Share Posted March 20, 2013 The first one is a rarely used (but not useless) pattern. Here's the best explanation I could find on the matter: http://kangax.github.com/nfe/#named-expr The important thing to realize is that the function name "functionName" is only available for use within the function definition itself. You may, for example, want to use it for recursion, etc. Anywhere outside the function definition though, the "functionName" function can only be referenced/called by using the someVar variable. Link to comment Share on other sites More sharing options...
Roy Posted March 21, 2013 Author Share Posted March 21, 2013 Thank you both for the information. It is greatly appreciated! Link to comment Share on other sites More sharing options...
Recommended Posts