views:

145

answers:

5

I was reading that using anonymous functions in javascript is bad practice, because it can make debugging a pain, but I haven't seen this for myself. Are anonymous functions in JavaScript really bad practice and, if so, why?

+8  A: 

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.

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

Kevin
Actually, this is one reason I've stopped using jQuery. It always took far longer than I thought reasonable to determine whether a bug was a syntax error in my code, a logical error in my code, or something wrong with jQuery itself. You have to admit, a call stack of anonymous functions doesn't make things as terribly clear at-a-glance as one of named functions does.
Kev
You can always use a [named function expression](http://yura.thinkweb2.com/named-function-expressions/#named-expr).
Marcel Korpel
+4  A: 

I would say the contrary, lambdas ( alias ) make some expressions much more succinct. If you're binding multiple event handlers to multiple events it would be tedious giving a function name to each and every event handler, for example.

It's more helpful and time-conserving than not, even if it makes debugging a little bit harder but I rarely struggle with debugging because a function is anonymous. And you should use JSLint to make your life easier when coding.

meder
+4  A: 

Most definitely not, lambda functions are used all over the place, almost ubiquitous.

Jacob Relkin
+3  A: 

Anonymous function expressions are best practice in JavaScript.

adamse
+3  A: 

Just because everybody uses them doesn't make them good practice (everybody remember using the table element for layout?). But, they're great because they can help clarify and simplify your code, giving less opportunity for something to go wrong.

But, anonymous functions shouldn't be so complicated that debugging becomes difficult with them. In that case, perhaps it's better to make a new function.

palswim
You can always use a [named function expression](http://yura.thinkweb2.com/named-function-expressions/#named-expr).
Marcel Korpel
+1 for lemming code
Brian S