Hacker News new | ask | show | jobs
by reycharles 3742 days ago
The ES6 "fix" is an abomination in my opinion. You're closing over a mutable variable, so you should see the mutations! IMO the real fix would be to write

    for (var i = 0; i < 5; i++) {
        let i_ = i;
        /* use i_ in the closure */
    }
In your ES6 solution if you e.g. increment "i" inside the loop after the closure the closure will see the mutation!

The real cause of confusion is mutation and javascript's scoping rules.

2 comments

If you write `let data = data;` in the closure, then you can achieve the effect of `move` without the special syntax (unless `data` can be copied, in which case there is really no way to force it to be moved inside the closure without `move`).

However, in Rust, you get an error if you accidentally capture by reference in the closure passed to `thread::spawn` so it's not as hard to get right as it is in JS.

ES6 fix is:

      for(let i = 0; i < 5; i++) {
          // no hacks needed if you don't use ES5 var
      }