user2755778
user2755778

Reputation: 53

Javascript closure anomoly

The output from this script is: [ [ 1, 2, 3, 4 ], 10 ] [ [ 91, 92, 93, 94 ], 10 ] [ [ 8888, 8888, 8888, 8888 ], 10 ] [ [ 'one', 'two', 'three', 'four' ], 10 ]

But if I un-comment hogs = [2, 4, 6, 8], the output is: [ [ 1, 2, 3, 4 ], 10 ] [ [ 1, 2, 3, 4 ], 10 ] [ [ 1, 2, 3, 4 ], 10 ] [ [ 1, 2, 3, 4 ], 10 ]

If I leave it commented out but un-comment hogs = [333, 444, 555, 666], the output is: [ [ 1, 2, 3, 4 ], 10 ] [ [ 91, 92, 93, 94 ], 10 ] [ [ 8888, 8888, 8888, 8888 ], 10 ] [ [ 8888, 8888, 8888, 8888 ], 10 ]

I would like to understand simple javascript closures well enough to predict their behavior. Is that possible short of analysing the specs for the engine? I would also like to know why re-defining an entire array in one statement has such drastically different side effects from re-assigning the array's individual values one at a time. I am afraid to get very creative because I don't know how to predict side effects, and I can't find a clue in the literature.

var x = 10;
var hogs = [1, 2, 3, 4];
var array5 = (function () {
    var ar = [];
    var z = x;
    var w = hogs;
    function g() {
        ar.push(w);
        ar.push(z);
        return ar;
    } return g;
})()();

console.log(array5);

//hogs = [2, 4, 6, 8];  Uncommenting this prevents array5 from changing.     
x = 40;
hogs[0] = 91;
hogs[1] = 92;
hogs[2] = 93;
hogs[3] = 94;
console.log(array5);

hogs[0] = 8888;
hogs[1] = 8888;The output from this script is:
hogs[2] = 8888;
hogs[3] = 8888;
console.log(array5);

// hogs = [333, 444, 555, 666]; Un-commenting this prevents.. 

hogs[0] = 'one';
hogs[1] = 'two';
hogs[2] = 'three';
hogs[3] = 'four';
x = 40;
console.log(array5);

I don't think you were being repetitive; you elegantly put the whole thing in a nutshell when you wrote "You are not saying 'tell the variable w to reference whatever object hogs references". What you are saying is "tell the variable w to reference whatever object hogs references at this current moment'" You were kind to take the time to explain this in detail. Perhaps you empathized with someone learning the language who simplistically imagined that the search for a variable value proceeded outwards through the scope chain all the way to Object object if necessary, while in this case the value in the enclosing function is ignored until the value in global scope is obliterated by a new definition. It is good to know that changing the values in an array maintains the array itself, intact but with some new or changed value assignments; and that is very very different from redefining an array, making the variable point to something entirely new. Images of some objects in memory standing still while others disappear and reappear elsewhere in memory dance in my head; which rhymes with "time for bed." For anyone else who might be interested in this, the analogous situation seems to exist for all objects, as illustrated by the following code:

enter code here
var x = 10;
var hogs = {'a': 1, 'b': 2, 'c' : 3, 'd' : 4};
var obj = {};
obj.h = hogs;

var ob5 = (function (arg) {
    function g() {
        var w = arg;
        return w;
    } return g;
})(hogs)();

console.log(ob5);

//hogs = [2, 4, 6, 8];  Uncommenting this prevents array5 from  changing.
x = 40;
hogs['a'] = 91;
hogs['b'] = 92;
hogs['c'] = 93;
hogs['d'] = 94;
console.log(ob5);

hogs.a = 8888;
hogs.b = 8888;
hogs.c = 8888;
hogs.d = 8888;
console.log(ob5);

hogs = {'a':333, 'b':444, 'c':555, 'd':666}; // Prevents further changes.

hogs.a = 'one';
hogs.b = 'two';
hogs.c = 'three';
hogs.d = 'four';
x = 40;
console.log(ob5);

Upvotes: 3

Views: 127

Answers (2)

DaoWen
DaoWen

Reputation: 33019

The closure returns the current value of hogs at the time it's applied (called). If you update hogs to point to a new array later, array5 (the result of calling your closure) still references the old copy. Your updates are only reflected in the current copy of hogs, so wherever you change it is the end of where your updates will be reflected by array5.

You could apply the closure again and you'll get a new value reflecting the current value of hogs, but you'd have to assign it a name (put it in a variable) to reference it again.


That's what I thought, and what I would have predicted. But I don't get that predicted behavior unless I include (un-comment) the line: hogs = [2, 4, 6, 8]. That freezes array5 at its value prior to "hogs = [2, 4, 6, 8]." Otherwise, array5 acts like a reference to the current value of hogs. I don't know how that behavior might have been predicted, and I can't explain it after the fact. Does it make sense to you?

Yes, that's how you should expect it to act. Arrays are mutable objects, and so changing the array in one place will be reflected anywhere else you change it. What you're doing really isn't much different than this:

var x = [1, 2, 3];
var y = x;
var x[0] = 4;
// What would you expect the value of y to be here?

If you really want to have a copy of the array, then you should make an explicit copy with the slice() method:

var array5 = (function () {
    var ar = [];
    var z = x;
    var w = hogs.slice(); // <== Explicit copy!
    function g() {
        ar.push(w);
        ar.push(z);
        return ar;
    } return g;
})()();

Upvotes: 3

Adam Jenkins
Adam Jenkins

Reputation: 55623

This is long winded and repetitive, but I try to explain it in a few different ways so you'll understand it:

There is an array in memory of value [1,2,3,4]. The way to access this array is by it's name, "hogs".

The variable w in the closure also points to this same array in memory, but it points to it by the name w. So now there are two ways to access the same array in memory, depending on what scope you are in - outside the closure, you ask for "hogs", inside the closure, you ask for "w" - in either caes, you get the same object back - an array of [1,2,3,4]

If you set "hogs" to another array - i.e. [2,4,6,8] - the original array - i.e. [1,2,3,4] - still exists in memory, but not it can no longer be accessed by "hogs" it is only accessible within the closure by asking for "w".

So, when you have the line

hogs = [2,4,6,8]

commented out and you do

 hogs[0] = 91

you are changing the first item of the array [1,2,3,4] in memory (that both hogs and w point to) to 91. At this point, w (inside the closure) and hogs (outside the closure) are still referencing the same array in memory.

If you uncomment the line

hogs = [2,4,6,8]

then hogs and w are now referencing two different arrays - hogs references an array with values [2,4,6,8] and w references a different array with values [1,2,3,4].

So then when you say

hogs[0] = 91

hogs now references an array that looks like this:

hogs = [91,4,6,8]

but w, because it is not referencing the same array as hogs, still contains the values:

w = [1,2,3,4]

If you're with me up to this point - then just read the rest of the code as it is. If w now references an array of [1,2,3,4], then, by reading the code in the closure, the value of w never changes (because there is no way to access it from outside it's closure). Hence, you will never be able to change the value that is returned from array5 - that's why you can call it over and over again while changing the values of the array hogs but you'll always get the same object returned - because hogs now references a different array than w you are never changing any of the values in w when you are changing the values in hogs

That's the best I can do.

EDIT

I guess the key point here is to say that at the line:

var w = hogs

You are not saying "tell the variable w to reference whatever object hogs references". What you are saying is "tell the variable w to reference whatever object hogs references at this current moment"

Therefore, when you tell hogs to reference a different object (an array - [2,4,6,8]), w still holds a reference to the object the hogs originally reference (an array - 1,2,3,4])

Sorry for being repetitive.

Finally, I guess the original commenter was correct - this is not a closure concept so much as a variable referencing concept.

Upvotes: 1

Related Questions