← Back to context

Comment by Lerc

1 day ago

consider this

   for (let i=0;i<3;i++) {
       i+=10;
       setTimeout(_=>console.log(i),30);
       i-=10
     }

Capture by value would print 10, 11, 12 that's the value when it was captured

Capture by reference would print 0,1,2

It's much easier to conceptualise it as

     for (const i=0;i<3;i++) {
      setTimeout(_=>console.log(i),30);
     }

which is fine because i never changes. It is a different i each time.

fancier example

    for (let x = 0, y = 0; y < 2; x=x++<3?x:y++,0){
        x+=10;
        y+=10;
        console.log("inline:",x,y);
        setTimeout(_=>console.log("timeout",x,y),30);
        x-=10;
        y-=10;
    }

> which is fine because i never changes. It is a different i each time.

This is clearly a super weird hack to make closure capture behave more like you'd want. There's a reason this level of weirdness isn't needed in C++.