node.js keep the local variable in function, why?

I have a question when I do the node.js async coding. Here is the example codes:

function foo(arg) {
  var a = arg;
  console.log(a + ' start');
  setTimeout(function () {console.log(a);}, 500);
};
foo(1);
foo(2);

It outputs:

1 start
2 start
1
2

I'm confused. I thought it should output↓, because the local variable is changed by the foo(2)

1 start
2 start
2
2

Could you guys please tell me why/how node.js keep the local variable for the internal callback function access? Thanks a lot!

Because it is a local variable, not a global. That's the point of local variables.

var a creates a variable that exists for the life time of the function call. Declaring a function inside it extends the lifetime to cover that function too. When the anonymous function is called it continues to use the a that exists in the scope that it was created in.

Since you call the outer function twice, you have two as. One for each call. You have two anonymous functions, one for each call. Each anonymous function was created in the same scope as one of the as.

JavaScript variables are scoped by function declarations, not by blocks. Thus, you are using two different variables.

It's working exactly as it should be. You declared the variable a inside your function with var a; and that, how you know, declare a local variable. The callback of setTimeout is inside the same scope as your function is (and so is your var a). That being said it's only a matter of understanding how scopes works. Here is an old and good post about it: http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/

Or you can just search for 'javascript scopes' on google and you will find plenty of a reference.