3 ms·
JS has this error too, but nothing forces Java to have this issue if they fix the no-mutable-captures problem. Dart got this right from the start. Here's JS s
by ErikCorry 2y ago
JS has this error too, but nothing forces Java to have this issue if they fix the no-mutable-captures problem. Dart got this right from the start.
Here's JS showing the same issue.
for (var i = 0; i < 10; i++) {
array.push(() => i)
}
array.forEach((fn) => console.log(fn())) // Prints 10 every time.
The correct fix is that each loop iteration gets a fresh i instead of i just being mutated. Currently you can't see the difference in Java between there-is-only-one-i and there-is-a-fresh-i-every-time, so Java is free to do this right.
- cess11 2y agoHere's what I'd do: array = []; function clos(val) { return () => val; } for (var i = 0; i < 10; i++) { array.push(clos(i)); } array.forEach(fn => console.log(fn())); This outputs 0-9 instead of 10, though I'm just a silly self-taught person that never got schooled at these things, maybe there is some reason not to use closures that I don't know about.
- ifwinterco 2y agoThese days in JS you can just use let instead of var and it will work, but in itself that inconsistency is a bit weird
- cess11 2y agoYeah, let/const is what I tend to use. Here I wanted to change someone else's code as little as possible. Edit: Oh, right, it also solves the 10-issue. Thanks, didn't realise at first.