A while
loop repeatedly executes a block of code as long as a specified condition remains true. The condition is evaluated before each iteration, and if it becomes false, the loop terminates.
Example 1: Basic Counter
// Initialize a counter variable
let count = 1;
// Loop as long as count is less than or equal to 5
while (count <= 5) {
console.log(`The count is: ${count}`);
// Increment the counter
count++;
}
Explanation
This code initializes a count
variable to 1. The while
loop continues to execute as long as count
is less than or equal to 5, printing the current count and then incrementing it in each iteration.
Example 2: Sum of Numbers
// Initialize variables for the sum and the current number
let sum = 0;
let number = 1;
// Loop to sum numbers from 1 to 10
while (number <= 10) {
sum += number;
// Move to the next number
number++;
}
console.log(`The sum of numbers from 1 to 10 is: ${sum}`);
Explanation
This example calculates the sum of numbers from 1 to 10. The while
loop adds the value of number
to sum
and increments number
until it is greater than 10.
Example 3: Array Iteration
// An array of fruits
const fruits = ['apple', 'banana', 'cherry'];
let i = 0;
// Loop through the array using a while loop
while (i < fruits.length) {
console.log(`Fruit: ${fruits[i]}`);
// Increment the index
i++;
}
Explanation
This code demonstrates iterating through an array. The while
loop runs as long as the index i
is less than the length of the fruits
array, printing each fruit to the console.
Example 4: Guessing Game
// The correct number to guess
const correctNumber = 7;
let guess = 0;
// Loop until the guess is correct
while (guess !== correctNumber) {
guess = parseInt(prompt("Guess a number between 1 and 10:"));
}
console.log("You guessed the correct number!");
Explanation
This simple guessing game uses a while
loop to repeatedly prompt the user for a guess. The loop continues until the user's guess
matches the correctNumber
.
Example 5: Countdown
// Starting number for the countdown
let countdown = 10;
// Loop as long as countdown is greater than 0
while (countdown > 0) {
console.log(`T-minus ${countdown}`);
// Decrement the countdown
countdown--;
}
console.log("Blast off!");
Explanation
This while
loop creates a countdown from 10. In each iteration, it prints the current countdown
value and then decrements it, stopping once countdown
reaches 0.
Example 6: Find First Even Number
// An array of numbers
const numbers = [1, 3, 5, 8, 9, 12];
let index = 0;
// Loop until an even number is found
while (numbers[index] % 2 !== 0) {
index++;
}
console.log(`The first even number is ${numbers[index]} at index ${index}.`);
Explanation
This code searches for the first even number in an array. The while
loop continues as long as the number at the current index
is odd, incrementing the index
to check the next element.
Example 7: Generate Random Number
// Initialize a random number
let randomNumber = 0;
// Loop until a number greater than 0.8 is generated
while (randomNumber <= 0.8) {
randomNumber = Math.random();
console.log(`Generated number: ${randomNumber}`);
}
console.log("A random number greater than 0.8 was generated.");
Explanation
This while
loop generates random numbers between 0 and 1. It continues to generate and print new numbers as long as the generated randomNumber
is less than or equal to 0.8.