0
let myPlaces = ['Place1', 'Place2', 'Place3'];
let friendPlaces = ['Place4', 'Place5', 'Place6'];

for (let myPlacesIndex = 0; myPlacesIndex < myPlaces.length; myPlacesIndex++) {
  console.log(myPlaces[myPlacesIndex]);
  for (let friendPlacesIndex = 0; friendPlacesIndex < friendPlaces.length; friendPlacesIndex++) {
    console.log(friendPlaces[friendPlacesIndex]);
  }
}

I don't understand the logic behind the inner "for loop" looping completely all at once. I expected the order that should have been printed to the console to be: Place1, Place4, Place2, Place5, Place3, Place6.

Can someone explain to me why that is?

Martineli
  • 89
  • 6
  • 3
    For every element in `myPlaces`, every element of `friendPlaces` is logged – Andrew Li Aug 09 '18 at 19:02
  • The answer to "why?" is that it's how the JavaScript specification says to do it. Step through the code in a debugger and you can see how it works (which is of course how @Li357 notes); – Heretic Monkey Aug 09 '18 at 19:08

1 Answers1

0

Because for is a sync loop. So when that instructions comes, it will execute all loops before going to next instruction. What means your output will be something like:

//Place-1 -> out for loop 1
//Place-4
//Place-5
//Place-6

//Place-2 -> out for loop 2
//Place-4
//Place-5
//Place-6

//Place-3 -> out for loop 3
//Place-4
//Place-5
//Place-6
joseatchang
  • 71
  • 1
  • 6