2.1 - While

Repeat, Repeat, Repeat, Repeat...

Reminder

  • Unit 0 - At this point you should be finished up to 0.5 with 0.6 this week.


Review

  • We can do the following with code:

    • control input & output

    • store values and manipulate them

    • control code with if-statements

    • "chunk" code in functions that run when commanded.

Repeating code is inefficient. And what if we don't know when it should end?

// Ask the user to enter a number and check for valid input
let
input = Number(prompt(“Enter a number.));

if (isNaN(input))
input = Number(prompt(“Please enter a number.));
if (isNaN(input))
input = Number(prompt(“Ugh, please enter a number.));
if (isNaN(input))
input = Number(prompt(“Enter a NUMBER.));
if (isNaN(input))
...

The ability to repeat, or loop, code provides lots of possibilities. The first loop we will look at is called the while loop and acts a lot like an if-statement.

// Example: A never-ending loop (not good)
while (true) {
console
.log("You can't stop me!");
}


// Example: Counting to 10
let n = 0;

while (n <= 10) {
console
.log("n is", n);
n
++; // We need to make sure we modify 'n'!
}


// Example: Should I stop?
let input = "n";

while (input.toUpperCase() != "Y") {
input = prompt("Should I stop? (y/n)");
}

console.log("Ok, I stopped");

Today's Task(s) / Homework

We will practice the While loop in Replit.