Jump to content
Larry Ullman's Book Forums
Roy

Question Regarding Named And Anonymous Funcitons Assigned To Variables

Recommended Posts

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?

Share this post


Link to post
Share on other sites

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!

  • Upvote 2

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...