It is copied (or assigned) in your second example, it's just that there's only one copy of variable j
and it will have the value that it last had in it which will be 9 (the last rev of your for loop). You need a new function closure to create a new copy of a variable for each rev of the for
loop. Your second example just has one variable that is common to all revs of your for
loop, thus it can only have one value.
I don't know of any definitive writeup on this topic.
Variables in javascript are scoped to the function level. There is no block scoping in javascript. As such, if you want a new version of a variable for each rev of the for loop, you have to use a new function (creating a function closure) to capture that new value each time through the for
loop. Without the function closure, the one variable will just have one value that will be common to all users of that variable.
When you declare a variable such as your var j = i;
at some location other than the beginning of the function, javascript hoists the definition to the top of the function and your code becomes equivalent to this:
var j;
for (var i = 0; i < 10; i++)
{
j = i;
process.nextTick(function ()
{
console.log(j)
})
}
This is called variable hoisting
and is a term you could Google if you want to read more about it. But, the point is that there is only function scope so a variable declared anywhere in a function is actually declared once at the top of the function and then assigned to anywhere in the function.