For those who aren’t familiar, anonymous functions are exactly that: they are unnamed functions that do work and are usually triggered when something has happened.
For example, say that you want to do something when the
#button has been clicked. Then this is how you may go about doing that in jQuery:
A relatively common scenario – it’s not even that difficult to read. But if what happens when you want to do more than one thing in the context of the anonymous function?
It can get littered with conditionals, can become a pain to read, and generally just doesn’t fit well within a client-side application if you’re aiming for something that’s maintainable.
When faced with that in any other scenario, we usually just break the units of work up into their own function, right? It makes things easier to read, delegates responsibility, and even enhances reuse.
So why not do that in the case of anonymous functions in jQuery?
Sure, perhaps a handler for a
click event isn’t that complicated, but if you’re someone who’s jumping into dealing with someone else’s code, this seems to be a bit more readable, doesn’t it?
A Real World Example
- Write everything within the context of the anonymous function
- Write individual functions for each option and call them in the anonymous function
Obviously I’m a fan of latter, not only because of the readability and maintainability that it has, but also because it breaks down the code into pieces that are much easier to manage over time.
For example, here’s something straight from Mayer’s codebase:
I’m still using an anonymous function to wrap calls to the other functions related to the Customizer, but that’s because it has a single job and will only ever have a single job, but if I wanted to take this a step further, then I could do something like this:
The challenge, though, is that if you want to pass around something like a reference to the
jQuery function, then it helps to first wrap the functions in an anonymous function and pass that variable from there.
Sounds a bit confusing, doesn’t it? If I had to distill it down, it’d be this:
- Only use anonymous functions when they call other functions, pass required parameters, and are used once.
- Give your functions meaningful names and set them up as callbacks. It’s much easier for future developers (including yourself) to read and understand what’s going on.
As with anything related to writing code, this isn’t the right way to do something and these are examples are really, really simple.
Regardless, it’s a way that I’ve found to help write more maintainable code that I can easily work with over time rather than keeping so many anonymous functions in the code.