In JavaScript,
a 'let' inside the initializer of a for loop is captured by value, all the others are captured by reference.
I think it's fair to call that semantics "implicit".
I think it's fair to call that semantics "implicit".
The following code prints 1, 2, 3. It wouldn't do that if the variable was captured by value.
for (let i = 0; i < 3;) {
setTimeout(() => console.log(i));
i++;
} 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 capturedCapture 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;
}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++.