JavaScript - 19

JavaScript - 19: While Loops

A while loop repeats code as long as a condition stays true.

Your challenge: Use one loop to count from 1 to 10, then use another to keep doubling a number until it becomes greater than 100.

✦ JavaScript Editor
▶ Live Output

How a while loop works

A basic loop looks like: while (condition) { ... }

JavaScript checks the condition before each repetition. If it is true, the loop runs again.

Count from 1 to 10

Start with: let count = 1;

Then use: while (count <= 10)

Inside the loop, print count and increase it with: count++;

Double a number

Start with: let number = 2;

Then use: while (number <= 100)

Inside the loop, print the number and double it: number = number * 2;

Watch out for infinite loops

If the value controlling the condition never changes, the loop may never stop.

For example, if count++ were missing, count <= 10 could stay true forever.

Try it: Change the starting number in the second loop and see how many times it doubles before passing 100.

Small experiment: Change count++ to count = count + 2 and see which numbers are printed.

Good JavaScript habit: Before running a while loop, make sure something inside the loop will eventually make the condition false.

👀 Show Solution
let count = 1;

while (count <= 10) {
  console.log("Count:", count);
  count++;
}

let number = 2;

while (number <= 100) {
  console.log("Doubling:", number);
  number = number * 2;
}

The first loop stops after count reaches 11. The second stops once number becomes greater than 100.