I’ve started to use Javascript a lot more, and as a result I am writing things complex enough that organization is becoming a concern. However, this question applies to any language that allows you to nest functions. Essentially, when should you use an anonymous function over a named global or inner function?
At first I thought it was the coolest feature ever, but I think I am going overboard. Here’s an example I wrote recently, ommiting all the variable delcarations and conditionals so that you can see the structure.
function printStream() {
return fold(function (elem, acc) {
...
var comments = (function () {
return fold(function (comment, out) {
...
return out + ...;
}, '', elem.comments);
return acc + ... + comments;
}, '', data.stream);
}
I realized though (I think) there’s some kind of beauty in being so compact, it is probably isn’t a good idea to do this in the same way you wouldn’t want a ton of code in a double for loop.
Like any tool, it depends. You shouldn’t always use it nor should you never use it. You should use it where appropriate.
You should use them where it’s a simple 2 or 3-liner and there is no application for using it anywhere else.
You should use it in JavaScript where you gain a closure to isolate variables in the deal.
Above all, as long as another developer can look at the code and “get it”, it’s just fine. When I look at the code sample above, I do not “get it.”