What rules govern the copying of variables in Javascript closures?

Posted by int3 on Stack Overflow See other posts from Stack Overflow or by int3
Published on 2010-03-21T17:52:54Z Indexed on 2010/03/21 18:01 UTC
Read the original article Hit count: 161

Filed under:
|

I'd just like to check my understanding of variable copying in Javascript. From what I gather, variables are passed/assigned by reference unless you explicitly tell them to create a copy with the new operator. But I'm a little uncertain when it comes to using closures. Say I have the following code:

var myArray = [1, 5, 10, 15, 20];
var fnlist = [];
for (var i in myArray) {
    var data = myArray[i];
    fnlist.push(function() {
        var x = data;
        console.log(x);
    });
}
fnlist[2](); // returns 20

I gather that this is because fnlist[2] only looks up the value of data at the point where it is invoked. So I tried an alternative tack:

var myArray = [1, 5, 10, 15, 20];
var fnlist = [];
for (var i in myArray) {
    var data = myArray[i];
    fnlist.push(function() {
        var x = data;
        return function() {
            console.log(x);         
        }
    }());
}
fnlist[2](); // returns 10

So now it returns the 'correct' value. Am I right to say that it works because a function resolves all variable references to their 'constant' values when it is invoked? Or is there a better way to explain it?

Any explanations / links to explanations regarding this referencing / copying business would be appreciated as well. Thanks!

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about closures