Using Named Callback Functions In Javascript Methods

Posted August 16, 2010 at 10:14 AM by Ben Nadel

Tags: Javascript / DHTML

After learning that I could use named functions within self-executing function blocks in Javascript, I was curious to see how else named functions might be used. For instance, can they be used in the creation of closures? Closures in Javascript are simply awesome. We use them all the time - probably way more than we are even conscious of; just think about how many times we pass around event handler callbacks and iteration callbacks in jQuery. Typically, closures are created with anonymous functions; but, can they be created with named functions? And if so, what kind of scoping do they have?

To test this, I created a demo using Javascript's String Replace() method. In addition to simple string replace functionality, the String.replace() method also allows us to use a callback handler in order to provide the iteration's replace logic. Typically, I use an anonymous function in this situation; but this time, I am using a named function:

  • <!DOCTYPE html>
  • <html>
  • <head>
  • <title>Named Callback Functions In Javascript</title>
  • <script type="text/javascript">
  •  
  • // Create a character string to test with.
  • var data = "hello world";
  •  
  • // Now, replace the vowels in the string with stars.
  • // Notice that the callback used in the replace function
  • // is being defined as a named-function.
  • var noVowelData = data.replace(
  • new RegExp( "[aieou]", "gi" ),
  • function replaceLogic( $0 ){
  • return( "*" );
  • }
  • );
  •  
  • // Log results.
  • console.log( noVowelData );
  •  
  • // Log the named function defined in the replace() method.
  • console.log( replaceLogic );
  •  
  • </script>
  • </head>
  • <body>
  • <!-- Intentionally left blank. -->
  • </body>
  • </html>

As you can see here, I have passed the named function, replaceLogic(), into the replace() method. The logic of the replaceLogic() function is such that it replaces incoming vowels with the "*" character. Once the replace method has executed, I am logging both the resultant string and the named-callback reference to the console. Here is the console output that I get:

h*ll* w*rld
replaceLogic is not defined

As you can see, Javascript's String replace() method was able to execute successfully using the named callback. However, as you can also see from the second line of the console output, the named callback was not bound to the calling context. From further logging (not shown), it appears that the replaceLogic variable is only available to the local execution of the replace function (such that it might be called recursively - not that that would be of any value to us in this particular situation).

I had no idea that it was valid to use named functions in this context, or in the self-executing function block context; however, I kind of like it. I don't know if I can see the best use-cases for it just yet but, it never hurts to have a few more tools in the toolbox.

NOTE: Regarding my intro, I think self-executing functions might create closures as well.




Reader Comments

Aug 16, 2010 at 6:36 PM // reply »
2 Comments

I too like using named functions over anonymous functions. But i remember reading about some problems with it, just can't remember what exactly.

A quick google search found this IE bug, which may be what I am thinking of:
http://yura.thinkweb2.com/named-function-expressions/#jscript-bugs


Aug 16, 2010 at 9:07 PM // reply »
10,743 Comments

@Tauren,

Apparently, Javascript has a number of little oddities. The other day, I came across this site:

http://wtfjs.com

Just a list of things that don't make sense.


Aug 17, 2010 at 10:48 AM // reply »
2 Comments

I found this article best for understanding named function http://yura.thinkweb2.com/named-function-expressions/


Aug 17, 2010 at 9:03 PM // reply »
10,743 Comments

@Nick,

Wow - that's a beasty article. I read about half of it (more than my brain can handle tonight). I never really though of a difference between function declarations and function expressions (and how they differ in behavior). Thanks for pointing this out.


Aug 19, 2010 at 3:29 PM // reply »
1 Comments

Hi Ben,

Nice post!

I've got this scenario mentally classified as "an anonymous function which has a name" (not that my definition is good, but I'm not sure if there is a good name out there for this type of function declaration).

In this scenario I believe that you can only use the name inside of the function itself. This is a definitive distinction when compared to "normal" named functions.

I haven't found any great use cases for this yet. For recursion I'm thinking argument.callee is gonna cover the use case.

Regardless - my brain now hurts just a little. Thanks for that!

Cheers,
Andrew


Aug 19, 2010 at 5:59 PM // reply »
2 Comments

@Andrew,

I had never really thought to use this technique for recursion as Ben pointed out, and there are plenty of other ways to accomplish recursion without needing to use named expressions. Still, it is interesting to consider.

The main use case I had for experimenting with them was in debugging and building a logger object. Having named functions and expressions produces much nicer stack traces, and the logger can actually output the name of the function it was in.

But in the end, I've resigned myself to not using this technique, as it isn't fully cross-browser compatible.

Tauren


Aug 21, 2010 at 3:21 PM // reply »
10,743 Comments

@Andrew,

Yeah, it's definitely an interesting thing, right? After reading the article that Nick posted, I think what's going on is that the function here, although it has a name, is a function "expression", not a function "declaration". As such, it is only available in that expression (unlike a function declaration which is actually pre-"compiled" so to speak). Very interesting stuff!

As far as using arguments.callee, the only "concern" there is that it is a deprecated approach. What does that mean? Probably nothing.

@Tauren,

Yeah, from what Ben Alman was saying in my other post, this is not a fully cross-browser compatible feature. Although, Alman did seem to imply that the issue was mostly with one particular mobile device.


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 16, 2012 at 8:18 PM
Best Of ColdFusion 10 Contest Entry - HTML Email Utility
Just found this, looks good! I'm trying to run it on local, it's the 64bit version and I'm experiencing horrible lag. On average the generate.cfm processes the content change in 60-90 seconds. I've ... read »
May 16, 2012 at 6:40 PM
Maintaining Sessions Across Multiple ColdFusion CFHttp Requests
I am trying to integrate this CFHTTPsession into an application that will log into zeekrewards.com to post ads and I am not having any luck. The code works perfectly for logging into other websites, ... read »
May 16, 2012 at 2:44 PM
Creating A Sometimes-Fixed-Position Element With jQuery
Thank you, very useful technique! Worked like a charm. ... read »
May 16, 2012 at 1:58 PM
Movies As A Religious Experience
Acting can, in a way, ruin the movie-goer's experience. I used to be able to get so caught up in movies and their plots, and totally engaged. But lately, I haven't been able to as much with a lot o ... read »
May 16, 2012 at 1:52 PM
The Science Of Optimal Post-Exercise Nutrition
children of this age eat very less vegetables so u can opt for salads they will like it also carrot ,cucumber,onion and as far as pulses are concerned u can boil them ,give him along with mashed rice ... read »
May 16, 2012 at 1:34 PM
Strange ColdFusion JRUN Stack Overflow Error
Hey, Recently I updated my jrun4 using the latest updater 7 and now i am having memory issues :(:(:( any help is appreciated ... read »
May 16, 2012 at 9:56 AM
ColdFusion 10 Beta, Apache Tomcat, And Symbolic Links On Mac OSX
Hi, Now that ColdFusion 10 is out I have stumbled over this as well and I cannot figure out the proper solution. We're running virtual hosts via Apache2; the ColdFusion-applications store their fil ... read »
May 15, 2012 at 6:03 PM
Movies As A Religious Experience
@Ben, I don't know whether you'd consider this a religious observation, but it seems to me, in a sense, movies multiply how many lives we get to have. Each movie is like a little extra life we get ... read »