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...
Help 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?
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
We will create a function (in Replit) that asks the user for a number (using prompt) and print stuff.
Instructions are in the comments, but essentially: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.