Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript : Omitted Initialize inside Nested For Loop

As we know, we can omit the initialization inside the for loop :

var i = 0;
for(; i < 10; i++) {
  // do Something with i
} 

However, i figure out if i omit the initialization inside the nested loop as well:

var i = 0;
var j = 0;
for(; i < 10; i++) {
  for(; j < 10; j++) {
     // only do Something with j
     // outner loop only run once
  }
}

Solution :

 var i = 0;
 var j;
 for(; i < 10; i++) {
   j = 0;
   for(; j < 10; j++) {
      // everything is fine!
   }
 }

Can anyone explain whats going on? I'm newbie in Javascript.

like image 728
Hunter Wei Avatar asked Apr 02 '26 02:04

Hunter Wei


1 Answers

The loop runs multiple times, but your 'j' is already ten after the first run of i, so the second loop no longer runs during the next values of i.

If you would write something like this.

  for(; i < 10; i++) {
     for(; j < 10; j++) {
           console.log("test")
      }  
      console.log("another test")
   }

You would see that both messages get printed 10 times.

The reason that your "j" loop, only runs "ten times once", is because you do not set J back to zero after it has run 10 times. So the statement j < 10is true for every loop if iafter the first run.

You could solve this by setting j = 0 inside the first for loop (if you do not want to put it inside the variable initialisation of the second loop.)

for(; i < 10; i++) {
    j = 0;
    for(; j < 10; j++) {
        console.log("test")
    }
    console.log("another test")
}
like image 133
Dylan Meeus Avatar answered Apr 04 '26 15:04

Dylan Meeus