4 ms·
I 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
by EvilTerran 10y ago
I 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.)