Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: confused about how nested for loops work

Why do nested for loops work in the way that they do in the following example:

var times = [
            ["04/11/10", "86kg"], 
            ["05/12/11", "90kg"],
            ["06/12/11", "89kg"]
];

for (var i = 0; i < times.length; i++) {
        var newTimes = [];
        for(var x = 0; x < times[i].length; x++) {
            newTimes.push(times[i][x]);
            console.log(newTimes);  


        }

    }

In this example I would have thought console.log would give me the following output:

["04/11/10"]
["86kg"]
["05/12/11"]
["90kg"]
["06/12/11"]
["89kg"]

However, I actually get this:

["04/11/10"]
["04/11/10", "86kg"]
["05/12/11"]
["05/12/11", "90kg"]
["06/12/11"]
["06/12/11", "89kg"]

Is anyone able to help me understand this?

EDIT:

Thanks for all your responses!

like image 447
Stephen Young Avatar asked Jun 04 '11 15:06

Stephen Young


People also ask

How do nested for loops work JavaScript?

JavaScript supports the nested loop feature, where a loop is present inside another loop. A loop can have one or number and/or n nested level of loops defined inside another loop. For each outer loop, the inner loop gets to execute.

What is wrong about nested loop?

Nested loops are frequently (but not always) bad practice, because they're frequently (but not always) overkill for what you're trying to do. In many cases, there's a much faster and less wasteful way to accomplish the goal you're trying to achieve.

How does the nested for loop works?

When a loop is nested inside another loop, the inner loop runs many times inside the outer loop. In each iteration of the outer loop, the inner loop will be re-started. The inner loop must finish all of its iterations before the outer loop can continue to its next iteration.

What is the difference between for in loop and for of loop in JavaScript?

Both for...in and for...of statements iterate over something. The main difference between them is in what they iterate over. The for...in statement iterates over the enumerable string properties of an object, while the for...of statement iterates over values that the iterable object defines to be iterated over.


4 Answers

You are redefining newTimes on every single loop and you are outputting to the console on each column push.

var times = [
            ["04/11/10", "86kg"], 
            ["05/12/11", "90kg"],
            ["06/12/11", "89kg"]
];
 var newTimes = [];
for (var i = 0; i < times.length; i++) {     
        for(var x = 0; x < times[i].length; x++) {
            newTimes.push(times[i][x]);
        }
    }
    console.log(newTimes);  

Returns: ["04/11/10", "86kg", "05/12/11", "90kg", "06/12/11", "89kg"] http://jsfiddle.net/niklasvh/SuEdt/

like image 77
Niklas Avatar answered Oct 27 '22 00:10

Niklas


// remember that the increment of the counter variable
// is always executed after each run of a loop


for (var i = 0; i < n; i++) {
    // some statement(s) to do something.. 

        // initializes child-loop counter in the first run of the parent-loop
        // resets child-loop counter in all following runs of the parent-loop
        // while i is greater than 0 and lower than n

    for (var j = 0; j < p; j++) {
        // some statement(s) to do something..

            // initializes grandchild-loop counter in the first run of the child-loop
            // resets grandchild-loop counter in all following runs of the child-loop
            // while j is greater than 0 and lower than p

        for (var k = 0; k < q; k++) {
            // some statement(s) to do something..
            // or add more internal loop-nestings if you like..
        }
    }
}

// if the counter variables of the descendent-loops were set before the loop-nesting,
// the inner loops would only run once, because the counter would keep the value
// of the abortion condition after the loop is finished
like image 45
scrypter Avatar answered Oct 27 '22 00:10

scrypter


Do this:

var newTimes = [];
for (var i = 0; i < times.length; i++) {
        for(var x = 0; x < times[i].length; x++) {
            newTimes.push(times[i][x]);
            console.log(newTimes);  


        }

    }

You are re-initializing newTimes each time through the loop.

like image 26
Femi Avatar answered Oct 26 '22 23:10

Femi


You output would be appropriate if the log statement would read

console.log(times[i][x]);

Instead you output your complete new list newTimes which is initialized outside the inner loop and grows with each inner loop iteration.

like image 31
Howard Avatar answered Oct 27 '22 00:10

Howard