How does naming an anonymous function in JavaScript make a difference?

javascript

Solution

Not trying to be combative with Kolink, but he goes a bit too far in saying it is NOT a good example. What #14 has to do with (in the links you shared) are named function expressions (a different animal from function declarations). Regardlesss of where the function reference is passed, if you name your function expression, it will always have a way to call itself, from within itself. This name, that you give your function expression, is a name that only it knows; it does not exist in any external scope.

See here and here on MDN, for a further discussion about function expressions vs. function declarations. The second link, at the bottom, has a heading about named function expressions. It does have a use; see my Gist for an example of one-off recursive function, that adds nothing to the local or global variable scope (useful for one-off DOM traversal, for instance).

Also, Tobias (in his answer here) points out other good uses of named function expressions, namely, in debugging.

Problem

I am analyzing the following two urls from John Resig's site, but I am not understanding how giving a name to the anonymous function has made a difference. My understanding is that the name given to an anonymous function can only be used inside the function definition, and nowhere outside of it, but in the following links it is making a huge difference - http://ejohn.org/apps/learn/#13 - http://ejohn.org/apps/learn/#14 Any explanation or reference will be a great help. I am still confused with the following lines in #14 ``` var samurai = { yell: ninja.yell }; var ninja = {}; assert( samurai.yell(4) == "hiyaaaa", "The method correctly calls itself." ); ``` How is Samurai.yell method still able to point ninja.yell when ninja is now pointing to a blank object. Only difference between #13 and #14 is providing a name to the function expression in #14. Is ninja.yell COPIED to yell and NOT referenced or these kind of NAMED function expression have global scope in some scenario's like this ? Same thing happens in #13 and #14, only difference is that function is named in #14 and unnamed in #13 plus ninja = {} in #14 and ninja = null in #13. Is there any hidden concept about NAMED FUNCTION EXPRESSIONS that I am missing which makes #14 workable and #13 not workable.

Original source