3.1 - While

Repeat, Repeat, Repeat, Repeat...


Want to skip this lesson an go directly to the gist on Github? Click here.

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

Check out your task in this gist.