Onward to mastering JavaScript's while
loops! while
loops are a vital tool in programming, enabling the repeated execution of code while a specified condition remains true. Much like continuously cleaning a room until it's no longer messy, while
loops run as long as the condition is true.
while
loops in JavaScript repeat an action "while" a condition remains true. For instance, you might play outside while it's sunny outside. A simple example of a while
loop in JavaScript is:
JavaScript1let counter = 0; // Initialize with 0 2while (counter < 5) { // Loop while counter is less than 5 3 console.log(counter); // Print the counter 4 counter++; // Increment the counter by 1 after each loop iteration 5} 6/* 7Prints: 80 91 102 113 124 13*/
Here, we initialize a counter
with a value of 0
, and log the current counter
value while its value is less than 5
. When the value becomes >= 5
, the loop execution finishes.
A while
loop consists of two core parts: a condition and a body. While the condition is true, the code block (body) under the while
statement executes.
JavaScript1while (condition) { // Loop continues while the condition is true 2 // block of code 3}
Imagine a routine task, like a countdown from 5 to 1. A while
loop can conveniently handle this, as follows:
JavaScript1let number = 5; // Initialize with 5 2 3while (number >= 1) { // While number is at least 1 4 console.log('Number is:', number); // Print the number 5 number--; // Decrease the number by one after each iteration 6} 7/* 8Prints: 95 104 113 122 131 14*/
while
loops in JavaScript can use compound conditions with the use of &&
(and) or ||
(or). Consider this code, where you're saving money for a bicycle and will stop if you reach the target or once winter begins:
JavaScript1let savings = 0; // Starts with 0 savings 2let isWinter = false; // Starts when it's not winter 3 4while (savings < 100 && !isWinter) { // As long as savings is less than 100 and it's not winter 5 savings += 10; // Save 10 more 6 console.log('Savings:', savings); 7 8 // Simulate the changing of seasons 9 if (savings === 50) { // When savings is 50, winter begins 10 isWinter = true; 11 } 12} 13/* 14Prints: 15Savings: 10 16Savings: 20 17Savings: 30 18Savings: 40 19Savings: 50 20*/
Take care to avoid creating an infinite loop, where the condition remains true, and the loop never stops. Here's an example where the increment is missing, which results in an infinite loop:
JavaScript1let counter = 0; // Initial counter value 2 3while(counter < 5) { // Counter is always less than 5 4 console.log(counter); 5 // counter++; 6 // Counter is not increasing (commented), creating an infinite loop 7}
Excellent! You've learned about while
loops, understood their syntax, and applied them in practical scenarios. Get ready for hands-on exercises to solidify these skills. Let's prepare for more JavaScript adventures!