Are anonymous functions a bad practice in JavaScript?

Nope, anonymous functions are used all over the place in JavaScript across the web. It may make debugging a little more difficult in spots, but not nearly enough to say that they shouldn't be used.

For example, JQuery makes extensive use of them.

There are a lot of times when you want to use them over formally declared functions, such as when you want to limit their scope.


I am going to go against the flow a little here and make the case that anonymous functions are indeed bad practice even though they are widely used.

1) Anonymous functions cannot be reused.

2) Anonymous functions, by definition, do not have a name and so do not describe what they do. Which is to say the code is not self documenting.

3) Anonymous functions cannot be tested in isolation with a unit testing framework.

4) I personally think they make code more difficult to read and debug. Though your experience may vary.

I do think there are situations where an anonymous function is the best choice and as a general rule in order to avoid the above downsides I almost always name my functions.

Typically the longer your anonymous function becomes the more likely that it would benefit from having a name.