4 ms·
Callback hell has confused me for a long time. I kept assuming there was a good reason people write code that way, and there was something wrong with naming my
by alanbernstein 10y ago
Callback hell has confused me for a long time. I kept assuming there was a good reason people write code that way, and there was something wrong with naming my functions and passing them by name. The latter approach always made more sense to me - it's more readable, and more intuitive.
If there is no real benefit to the nested anonymous function style, why do people do it that way? It would never even have occurred to me to write code like that if I didn't see it in javascript all over the place.
- EvilTerran 10y agoI can think of one advantage - lexical closure: when your callback's body is defined inside the calling scope, you can use variables from that scope inside the callback; and the callback can assign to those variables & have the change persist in the caller (only really relevant when the callback's invoked synchronously, but can be very useful in those cases - eg, with Array.prototype.forEach). It is possible to replicate these effects without closures, but it can get pretty messy: the former by prepending the variables to the callback's parameter list and .bind()ing them where you use it; the latter similarly, but you also have to introduce a layer of indirection via an object to get a "pass-by-reference"-like effect. So sometimes it really is simpler to just use a function expression in-place. To contrive a quick motivating example: var odds = 0, evens = 0; array.forEach(function (x) { if (x % 2) ++odds; else ++evens; }); console.log("odd:", odds, "even:", evens); versus function callback (counts, x) { if (x % 2) ++counts.odds; else ++counts.evens; } ... var counts = { odds: 0, evens: 0 }; array.forEach(callback.bind(this, counts)); console.log("odd:", counts.odds, "even:", counts.evens); (And yes, I know you can just use "for...of" for this particular scenario in modern JS; like I said, contrived example.)
- wvenable 10y agoA lot of one-time-use functions aren't necessarily more readable either. You can start to the lose the context of when, where, and why it's being called. Many small functions or nested anonymous functions are just two ways of dealing with a difficult situation.