Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the benefits to using anonymous functions instead of named functions for callbacks and parameters in JavaScript event code?

I'm new-ish to JavaScript. I understand many of the concepts of the language, I've been reading up on the prototype inheritance model, and I'm whetting my whistle with more and more interactive front-end stuff. It's an interesting language, but I'm always a bit turned off by the callback spaghetti that is typical of many non-trivial interaction models.

Something that has always seemed strange to me is that in spite of the readability nightmare that is a nest of JavaScript nested callbacks, the one thing that I very rarely see in many examples and tutorials is the use of predefined named functions as callback arguments. I'm a Java programmer by day, and discarding the stereotypical jabs about Enterprise-y names for units of code one of the things I've come to enjoy about working in a language with a strong selection of featureful IDE's is that using meaningful, if long, names can make the intent and meaning of code much clearer without making it more difficult to actually be productive. So why not use the same approach when writing JavaScript code?

Giving it thought, I can come up with arguments that are both for and against this idea, but my naivety and newness to the language impairs me from reaching any conclusions as to why this would be good at a technical level.

Pros:

  • Flexibility. An asynchronous function with a callback parameter could be reached by one of many different code paths and it could be harried to have to write a named function to account for every single possible edge case.
  • Speed. It plays heavily in to the hacker mentality. Bolt things on to it until it works.
  • Everyone else is doing it
  • Smaller file sizes, even if trivially so, but every bit counts on the web.
  • Simpler AST? I would assume that anonymous functions are generated at runtime and so the JIT won't muck about with mapping the name to instructions, but I'm just guessing at this point.
  • Quicker dispatching? Not sure about this one either. Guessing again.

Cons:

  • It's hideous and unreadable
  • It adds to the confusion when you're nested nuts deep in a swamp of callbacks (which, to be fair, probably means you're writing poorly constructed code to begin with, but it's quite common).
  • For someone without a functional background it can be a bizarre concept to grok

With so many modern browsers showing the ability to execute JavaScript code much faster than before, I'm failing to see how any trivial sort of performance gain one might get out using anonymous callbacks would be a necessity. It seems that, if you are in a situation where using a named function is feasible (predictable behavior and path of execution) then there would be no reason not to.

So are there any technical reasons or gotchas that I'm not aware of that makes this practice so commonplace for a reason?

like image 467
Doug Stephen Avatar asked Apr 22 '12 23:04

Doug Stephen


People also ask

What is the benefit of anonymous function in JavaScript?

The advantage of an anonymous function is that it does not have to be stored in a separate file. This can greatly simplify programs, as often calculations are very simple and the use of anonymous functions reduces the number of code files necessary for a program.

What is the purpose of anonymous function?

Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class. printf("Hello %s\r\n", $name);

Why do we need anonymous function in Java?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

What is the difference between a named function and an anonymous function?

TL;DR Named functions are useful for a good debugging experience, while anonymous functions provides context scoping for easier development. Arrow functions should only be used when functions act as data.


2 Answers

I use anonymous functions for three reasons:

  1. If no name is needed because the function is only ever called in one place, then why add a name to whatever namespace you're in.
  2. Anonymous functions are declared inline and inline functions have advantages in that they can access variables in the parent scopes. Yes, you can put a name on an anonymous function, but that's usually pointless if it's declared inline. So inline has a significant advantage and if you're doing inline, there's little reason to put a name on it.
  3. The code seems more self-contained and readable when handlers are defined right inside the code that's calling them. You can read the code in almost sequential fashion rather than having to go find the function with that name.

I do try to avoid deep nesting of anonymous functions because that can be hairy to understand and read. Usually when that happens, there's a better way to structure the code (sometimes with a loop, sometimes with a data table, etc...) and named functions isn't usually the solution there either.

I guess I'd add that if a callback starts to get more than about 15-20 lines long and it doesn't need direct access to variables in the parent scope, I would be tempted to give it a name and break it out into it's own named function declared elsewhere. There is definitely a readability point here where a non-trivial function that gets long is just more maintainable if it's put in its own named unit. But, most callbacks I end up with are not that long and I find it more readable to keep them inline.

like image 158
jfriend00 Avatar answered Oct 02 '22 15:10

jfriend00


I prefer named functions myself, but for me it comes down to one question:

Will I use this function anywhere else?

If the answer is yes, I name/define it. If not, pass it as an anonymous function.

If you only use it once, it doesn't make sense to crowd the global namespace with it. In today's complex front-ends, the number of named functions that could have been anonymous grows quickly (easily over 1000 on really intricate designs), resulting in (relatively) large performance gains by preferring anonymous functions.

However, code maintainability is also extremely important. Each situation is different. If you're not writing a lot of these functions to begin with, there's no harm in doing it either way. It's really up to your preference.

Another note about names. Getting in the habit of defining long names will really hurt your file size. Take the following example.

Assume both of these functions do the same thing:

function addTimes(time1, time2) {     // return time1 + time2; }  function addTwoTimesIn24HourFormat(time1, time2) {     // return time1 + time2; } 

The second tells you exactly what it does in the name. The first is more ambiguous. However, there are 17 characters of difference in the name. Say the function is called 8 times throughout the code, that's 153 extra bytes your code didn't need to have. Not colossal, but if it's a habit, extrapolating that to 10s or even 100s of functions will easily mean a few KB of difference in the download.

Again however, maintainability needs to be weighed against the benefits of performance. This is the pain of dealing with a scripted language.

like image 41
Andrew Ensley Avatar answered Oct 02 '22 15:10

Andrew Ensley