Reck
Reck

Reputation: 8792

Javascript closures: primitive vs reference behaviour

I was hoping someone could explain to me what's going on in the code below. I'm finding it very hard to wrap my head around why this closure is treating primitives and references differently. I'm hoping I'm missing something obvious here.

function returnFunction(x, y) {
  return function() {
      alert("x:" + x + " - nb of elements in y:" + y.length);
  };
}

var f = 0;
var g = [];
var h = [];

for(var i = 0; i < 3; i++) {
  f += 1;
  g.push(i);
  h.push(returnFunction(f, g));
}

for(var i = 0; i < 3; i++) {
  h[i]();
}

// this is what gets returned
// x:1 - nb of elements in y: 3
// x:2 - nb of elements in y: 3
// x:3 - nb of elements in y: 3

// why do x and y get treated differently by js in this case?

Upvotes: 4

Views: 988

Answers (6)

The g array is modified 3 times and never copied. The primitives are passed by value and copied. Thus when the closure is defined, they keep the value from the previous loop. The last loop prints the lenght of the same array 3 times.

Upvotes: 0

rajuGT
rajuGT

Reputation: 6404

This is because, The context was bound to the reference, not to the snapshot of the reference when it got called/created.

Let us walk through the code, block by block to have more clarity

for(var i = 0; i < 3; i++) {
  f += 1;
  g.push(i);
  h.push(returnFunction(f, g));
}

The above loop executes 3 times, and each time it puts some value in g array and in h array.

So lets go inside, what the values are populated. Before that, be clear with this below code.

function returnFunction(x, y) {
  return function() {
      alert("x:" + x + " - nb of elements in y:" + y.length);
  };
}

Calling above function once, will return a function, calling it again meaning whatever reference you received at first time, It will display an alert. In short (returnFunction(5,[4,5,6])()) will display an alert "x:5 - nb of elements in y: 3". // It looks like the y is taking an array argument, because in alert we have y.length property.

Value populated

loop_number:

1. - - - - f = 1 - - - - g = [1] - - - - h[return function when called with (1, array-g[1])]

2. - - - - f = 2 - - - - g = [1,2] - - - - h[return function when called with (1, array-g[1]), return function when called with (2, array-g[1,2])]

3. - - - - f = 3 - - - - g = [1,2,3] - - - - h[return function when called with (1, array-g[1]), return function when called with (2, array-g[1,2]), return function when called with (3, array-g[1,2,3])]

Finally

for(var i = 0; i < 3; i++) {
  h[i]();
}

We are looping over h array, i.e. values we had in array h at loop-3 in the above explanation. It has inner function which already has the context values. i.e. it knows what is x and what is y when each time called. Remember, the second parameter was an h array reference we sent.

So if we execute those function like h[i](), it executes with first x's primary value and y array reference. Even though when we are calling the returnFunction with g array and it had only one value, the returned function is bound with the reference, not at that snapshot what it had. So the output is printing array size as // x:1 - nb of elements in y: 3

And the same goes on for 2nd and 3rd loop while executing returnFunction.

Upvotes: 5

user2844991
user2844991

Reputation:

Primitive types contain the actual data, while reference types contain only a memory address (a pointer to the memory location where the object's data resides).

So when you want to check the length field of your array (which is a reference type) you first need to find what is the memory address where the object's data resides (you look into y variable), you go to that address and finally you look at the data.

Now, when you call a function, for each parameter, a copy of their value is made and is stored in a local variable, available in your function scope. So every time you pass your array as a parameter, a copy of the memory address where the data resides is stored in a local variable (only the memory address is copied, not the whole object).

So, to answer your question: no, primitive and reference types are not treated differently when passed to a function. A copy is made in both cases, except the primitives contain the actual data, while references do not, they contain an address (a pointer to the actual data). When you follow the address you get the data, but the data might have been modified between the time you made a copy of the address and the time you checked the data.

Upvotes: 4

4thex
4thex

Reputation: 1166

It is because the closure holds the reference to the argument. The g array gets modified before the function is invoked. To avoid this, you would need to make a copy of the array that is passed in, and store it in the function.

Upvotes: 0

Oriol
Oriol

Reputation: 288450

That's because the inner function has only a reference to the array, and that array is altered before the function is called.

You can fix it by only accessing primitive values in the inner function.

function returnFunction(x, y) {
  var len = y.length; // Primitive value
  return function() {
      alert("x:" + x + " - nb of elements in y:" + len);
  };
}

Alternatively you can copy the array. Even if the original array is changed outside, the copy won't be altered.

function returnFunction(x, y) {
  y = y.slice(); // Copy it
  return function() {
      alert("x:" + x + " - nb of elements in y:" + y.length);
  };
}

Upvotes: 0

leeor
leeor

Reputation: 17801

the g array is defined outside the scope of returnFunction. Javascript is always pass by value. In the case of a reference, the reference itself is copied, but it's still the original array object, hence the final value it repeated 3 times.

Upvotes: 0

Related Questions