Nesting Ugly Anonymous Functions

We all do it

If you’re a JavaScript developer (or even more likely if you’re a developer that dabbles with JavaScript) you’ll have written code like this many times:

1
2
3
4
document.addEventListener("click", function() {
// handler code ...
alert("document clicked and fired ugly nested function");
});

You might be thinking what’s wrong with that, but I hope you’re thinking I’m better than that, I’d do something like this:

1
2
3
4
5
6
var doStuff = function () {
// handler code ...
alert("document clicked and fired alert function");
};
document.addEventListener("click", doStuff);

Great. What do you do if the alert text is dynamic? I’ve seen all kinds of ugly messes that usually lead back to the first approach or result in timing and scoping issues.

This problem isn’t just limited to event handlers, ugly nested anonymous functions are frequently used in callbacks and iterators. This results in poorer performance and uglier, less maintainable and bug prone code.

The right frame of bind

Yes, I really did just make that joke, it’s been a long week. In all seriousness Function.prototype.bind is your friend here, it’ll help you clean up your messy code, like any good friend should. There are other ways to do this of course (JavaScript is wonderful for that):

1
2
3
4
5
6
var doStuff = function (message) {
// handler code ...
alert(message);
};
document.addEventListener("click", doStuff.bind(null, "document clicked"));

Clean, reusable and easier to maintain. Better than inlining or manipulating variables at a higher scope.

A good curry

You can’t beat a good curry, especially if you find yourself nesting iterator functions (ewww). I suggest you take a look at functional.js, or you can read earlier posts on my blog (first post here).