4.1 - Nested Loops

Review

In Unit 3 we learned how to control the flow of data. The major takeaways are the if-statement and the while-loop.


Lesson: 4.1 - 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

  • Helps with multiple dimensions {think Cartesian Plane - (x, y)}

  • The inner-loop will happen more often (every time the outer loop happens)

  • What will this print:

let y = 0;

while (y < 10) {

let x = 0;

let output = "";


while (x < 10) {

output += "🎃 ";

x++;

}

console.log(output);

y++;

}


4.1 Mini Task

  • Create a program (fork this Repl) that asks the user for a number (using prompt).

    • Your program will print that many emoji's (of your choice from this site) to the screen.

    • Then ask the user again. Repeat.

    • If the user enters "-1", the program ends.