JavaScript Loop While
JavaScript while Loop
Section titled “JavaScript while Loop”Loops are a fundamental control structure in programming, allowing you to execute a block of code repeatedly as long as a specified condition remains true.
The while Loop
Section titled “The while Loop”The while loop executes a block of code as long as a specified condition evaluates to true.
The condition is evaluated before executing the code block in each iteration.
Syntax:
Section titled “Syntax:”while (condition) { // code block to be executed // This block will run as long as 'condition' is true // Often includes a statement that eventually makes the condition false (e.g., incrementing a counter)}Example:
Section titled “Example:”In the following example, the code inside the loop will execute repeatedly as long as the variable i is less than 5:
let text = "";let i = 0;
while (i < 5) { text += `The number is ${i}\n`; i++; // Increment i to eventually make the condition false}
console.log(text);// Output:// The number is 0// The number is 1// The number is 2// The number is 3// The number is 4| Caution: | If you forget to include a statement that eventually makes the loop’s condition false (e.g., forgetting i++ in the example above), the loop will run forever. This is called an infinite loop and can crash your browser or script. |
|---|
The do…while Loop
Section titled “The do…while Loop”The do...while loop is a variant of the while loop. The key difference is that the do...while loop executes its code block once before checking the condition. Then, it will repeat the loop as long as the condition is true.
This ensures the code block is executed at least once, even if the condition is initially false.
Syntax:
Section titled “Syntax:”do { // code block to be executed // This block is executed at least once} while (condition);Example:
Section titled “Example:”The example below uses a do...while loop. The loop body will always execute at least once.
let result = "";let j = 0;
do { result += `Current value of j: ${j}\n`; j++;} while (j < 3);
console.log(result);// Output:// Current value of j: 0// Current value of j: 1// Current value of j: 2
// Example where condition is initially false:let k = 5;let runOnceText = "";do { runOnceText = "This runs even if k is not less than 5 initially."; k++;} while (k < 5);console.log(runOnceText); // Outputs the message because the block runs once.Remember to include logic within the loop to eventually make the condition false to avoid infinite loops.
Comparing for and while Loops
Section titled “Comparing for and while Loops”A while loop can often achieve the same results as a for loop. A for loop is generally preferred when the number of iterations is known or can be easily determined beforehand (e.g., iterating over an array with a known length).
Consider a for loop:
const cars = ["BMW", "Volvo", "Saab", "Ford"];let carListFor = "Cars (using for loop):\n";for (let i = 0; i < cars.length; i++) { carListFor += cars[i] + "\n";}console.log(carListFor);The equivalent using a while loop:
const cars = ["BMW", "Volvo", "Saab", "Ford"];let carListWhile = "Cars (using while loop):\n";let i = 0; // Initialization outside the loopwhile (i < cars.length) { // Condition carListWhile += cars[i] + "\n"; i++; // Increment/Update inside the loop}console.log(carListWhile);The original tutorial showed a for loop variant that looks very much like a while loop by omitting the initialization and final-expression parts within the for statement itself:
const carsArray = ["Audi", "Mercedes", "VW"];let outputText = "";let k_idx = 0;// This for loop structure is less common but valid; resembles a while loop.for (; carsArray[k_idx]; ) { outputText += carsArray[k_idx] + "\n"; k_idx++;}console.log("Cars (using for loop variant):\n" + outputText);// This works because carsArray[k_idx] will eventually be undefined (falsy) when k_idx is out of bounds.Choose the loop type that makes your code clearest and most maintainable for the specific task. For iterating over array elements, for...of loops or array methods like forEach() are often more modern and concise alternatives.
Further reading: MDN: while, MDN: do…while