JavaScript - While Loops

Hello there, future coding superstars! Today, we're diving into the exciting world of JavaScript while loops. As your friendly neighborhood computer teacher, I'm here to guide you through this journey with plenty of examples and explanations. So, grab your virtual backpacks, and let's embark on this loopy adventure!

JavaScript - While Loop

JavaScript while Loop

The while loop is like a persistent friend who keeps asking, "Are we there yet?" until you finally reach your destination. It's a fundamental tool in programming that allows us to repeat a block of code as long as a specified condition is true.

Basic Syntax

Here's what a while loop looks like in its simplest form:

while (condition) {
    // code to be executed
}

Let's break this down:

  • The while keyword tells JavaScript that we want to start a while loop.
  • The condition is a boolean expression that's evaluated before each iteration of the loop.
  • If the condition is true, the code inside the curly braces {} is executed.
  • This process repeats until the condition becomes false.

Example 1: Counting to 5

Let's start with a simple example:

let count = 1;

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

In this example:

  1. We initialize a variable count with the value 1.
  2. The while loop continues as long as count is less than or equal to 5.
  3. Inside the loop, we log the current count to the console.
  4. We increment count by 1 using the ++ operator.
  5. The loop repeats steps 3-4 until count becomes 6, at which point the condition becomes false, and the loop ends.

Output:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5

Example 2: Sum of Numbers

Let's try something a bit more practical. We'll use a while loop to calculate the sum of numbers from 1 to 10:

let sum = 0;
let number = 1;

while (number <= 10) {
    sum += number;
    number++;
}

console.log("The sum of numbers from 1 to 10 is: " + sum);

In this example:

  1. We initialize sum to 0 and number to 1.
  2. The loop continues as long as number is less than or equal to 10.
  3. In each iteration, we add the current number to sum.
  4. We increment number by 1.
  5. After the loop ends, we print the final sum.

Output:

The sum of numbers from 1 to 10 is: 55

JavaScript do...while Loop

Now, let's meet the do...while loop – the slightly more optimistic cousin of the while loop. It's like saying, "Let's do this at least once, and then we'll see if we want to continue."

Basic Syntax

Here's the structure of a do...while loop:

do {
    // code to be executed
} while (condition);

The key difference here is that the code block is executed at least once before the condition is checked.

Example 3: Guessing Game

Let's create a simple guessing game using a do...while loop:

let secretNumber = 7;
let guess;

do {
    guess = prompt("Guess a number between 1 and 10:");
    guess = Number(guess);

    if (guess === secretNumber) {
        console.log("Congratulations! You guessed it!");
    } else if (guess < secretNumber) {
        console.log("Too low! Try again.");
    } else {
        console.log("Too high! Try again.");
    }
} while (guess !== secretNumber);

In this example:

  1. We set a secretNumber and initialize guess.
  2. The loop prompts the user to guess a number and converts it to a number type.
  3. We check if the guess is correct, too low, or too high and provide feedback.
  4. The loop continues as long as the guess is not equal to the secret number.
  5. Even if the user guesses correctly on the first try, the loop body executes at least once.

JavaScript while vs. for Loops

Now that we've explored while loops, you might be wondering, "When should I use a while loop instead of a for loop?" Great question! Let's compare them.

When to Use While Loops

While loops are typically used when:

  1. You don't know in advance how many times the loop should run.
  2. The loop's continuation depends on a condition that might change during the loop's execution.

When to Use For Loops

For loops are often preferred when:

  1. You know exactly how many times the loop should run.
  2. You're iterating over a sequence (like an array) with a known length.

Example 4: Finding the First Power of 2 Greater Than 1000

Let's use a while loop to find the first power of 2 that's greater than 1000:

let power = 0;
let result = 1;

while (result <= 1000) {
    power++;
    result = Math.pow(2, power);
}

console.log(`The first power of 2 greater than 1000 is 2^${power} = ${result}`);

In this case, a while loop is perfect because we don't know in advance how many iterations we'll need.

Methods Table

Here's a handy table summarizing the methods we've discussed:

Loop Type Syntax Use Case
while while (condition) { ... } When the number of iterations is unknown
do...while do { ... } while (condition); When you want to execute the loop at least once
for for (init; condition; update) { ... } When the number of iterations is known

Remember, choosing the right loop is like picking the right tool for a job. With practice, you'll develop an intuition for which one fits best in different scenarios.

And there you have it, my coding apprentices! We've looped through the ins and outs of while loops in JavaScript. Remember, loops are like merry-go-rounds in the playground of programming – they keep things spinning until it's time to stop. Keep practicing, and soon you'll be the loop master of your coding universe!

Credits: Image by storyset