2.4 - Nested Loops

Review

We utilize scope blocks (curly braces) to {contain code}. This means that every time you use curly braces, you can use any code inside them that you want.


if (x > 10) {

  if (stop == 0) {

    while (x > stop) {

      if (x % 2 == 0) {

        console.log(x);

      }

      x--;

    }

  }

}

Nested Loops

We have seen that you can "nest" if-statements:

 if (paused == false) {

   // Get player movement

   move = getKeyPress();


   if (move == RIGHT) {

     // Move the player to the right

   }

 }


What happens when we put a loop inside another loop?

Nested Loops...

for (let y = 0; y < 10; y++) {

   let x = y + 1;

   let output = "";

   while (x > 0) {

     output += "🎃 ";

     x--;

   }

   console.log(output);

}


Nested Loops Mini Task