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 »
11,246 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 »
11,246 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 »
11,246 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
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 25, 2013 at 10:08 AM
Using "//" And ".//" Expressions In XPath XML Search Directives In ColdFusion
@Ben, my question is that i want the current node with its tag and its parent node. i just want only that data. So, give me the solution for that. and remember solution is working on " xpath 1.0 ... read »
May 25, 2013 at 10:01 AM
Using "//" And ".//" Expressions In XPath XML Search Directives In ColdFusion
hey ben, i want get my current node tag and also want the root node tag withing. So, how can i fix it.. ! ... read »
May 24, 2013 at 5:39 PM
Ask Ben: Manually Enforcing Basic HTTP Authorization In ColdFusion
@Adam Oops! My mistake! I hadn't gotten that far in my testing - I'm still baby stepping my way through the process. ... read »
May 24, 2013 at 5:13 PM
Ask Ben: Manually Enforcing Basic HTTP Authorization In ColdFusion
Hi Jason, Thanks for checking up on that, but I still stand firm on my position. :) There are actually two listLast()'s in use, and you're right that the one using a space as a delimiter is fine. ... read »
May 24, 2013 at 4:45 PM
Ask Ben: Manually Enforcing Basic HTTP Authorization In ColdFusion
@Ben I have been lurking your site for quite some time, and haven't stepped up to comment until today. Thanks for all the great info - keep it up! @Adam I believe you are mistaken... as the commen ... read »
May 24, 2013 at 11:21 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@WebManWalking, Ha ha, let's us never speak of justifying "##" notation again :P ... read »
May 24, 2013 at 11:18 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Ben, Ah, so it was indeed how I vaguely remembered it to be: A direct assignment value = users.id[ i ] causes value to retain the sticky datatype of the query column. Although unnecessary in ... read »
May 24, 2013 at 9:11 AM
Preventing Links In Standalone iPhone Applications From Opening In Mobile Safari
@Brandon, Hi, No, I haven't been able to do that. I have just kept it as it is. ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools