Use Caution When Reinitializing Variables Inside a Loop Question

The outer loop simply pushes an instance of rows[] onto the newArray[]. And it loops three times. So three times, you push a copy of rows.

But the point of the conversation regarding pass by value or pass by reference, while the rows variable is assigned by value, it’s contents (it seems) are handled by reference. So when the rows variable is updating, its reference at a global level is also updating each ‘copy’ in the newArray.

So initially, newArray = [] and rows = []. After the inner loop has completed the first time, newArray is still empty, but rows = [0,0]. At that point, rows gets pushed onto newArray, which makes newArray = [ [ 0,0 ] ]. Note that newArray is not a copy of rows – it is an array, of which its sole element is a reference to another (nested) array.

Now, the second outer loop begins. At the end of the inner loop, newArray = [ [ 0,0 ] ] and rows = [0,0,0,0]. As that has updated, it has updated the first reference in newArray, so when we push another copy of rows onto newArray, we get newArray = [ [0,0,0,0], [0,0,0,0] ] androws = [0,0,0,0]`.

Third time through the outer loop, rows updates as we go through the inner loop, but it also updates the references in newArray – so before we push rows onto newArray, it has already changed! It now looks like newArray = [ [0,0,0,0,0,0], [0,0,0,0,0,0] ] (two members, each a reference to rows, each six elements long). After we push ANOTHER copy of rows onto it, we get:

newArray = [ [ 0,0,0,0,0,0 ], [ 0,0,0,0,0,0 ], [ 0,0,0,0,0,0 ] ]
rows = [ 0,0,0,0,0,0 ]

In other words, newArray only contains references to that rows array. When the outer loop executes three times, it pushes that reference on three times. Rows, on the other hand (so long as you leave it in a global scope), continues to accumulate members, rather than re-initializing each iteration. That’s because the INNER loop, which is the only one changing rows, keeps pushing elements on. But that inner loop executes six times (twice for each inner loop, times three for the outer loop). Thus, rows ends up with six members.

8 Likes