Understanding variable capture by closures in Javascript/Node

closures, javascript, node.js

Solution

I don't have a handy reference. But the bottom line is: In the first, you're explicitly passing in `i` to an anonymous function, which creates a new scope. You are not creating a new scope for either `i` or `j` in the second. Also, JavaScript always captures variables, not values. So you would be able to modify i too.

The JavaScript `var` keyword has function scope, not block scope. So a for loop does not create a scope.

As a note, the non-standard `let` keyword has local scope.

Problem

Is there a definite source on variable capture in Javascript besides the standard (it's a pain to read the standard)? In the following code `i` is copied by value: ``` for (var i = 0; i < 10; i++) { (function (i) { process.nextTick(function () { console.log(i) }) }) (i) } ``` So it prints 1..10. `process.nextTick` is an analog of `setTimeout(f,0)` in node. But in the next code i doesn't seem to be copied: ``` for (var i = 0; i < 10; i++) { var j = i process.nextTick(function () { console.log(j) }) } ``` It prints 9 10 times. Why? I'm more interested in a reference/general article than in explaining this concrete case of capture.

Original source