While Loops
๐จโ๐ผ When you don't know exactly how many iterations you need,
while loops
continue running as long as a condition is true.The syntax:
while (condition) {
// code to repeat
}
For example:
let count = 0
while (count < 3) {
console.log(count)
count++
}
// Logs: 0, 1, 2
- Use a while loop to log numbers 1 through 5
- Create a variable
sumstarting at 0, and use a while loop to add numbers 1 through 10 to it, then log the final sum - Use a while loop to find the first number greater than 1 that divides evenly
into 100 (hint: start at 2 and check
100 % number === 0)
๐ฐ Remember to update your counter inside the loop, or it will run forever!
Infinite loop warning! If the condition never becomes false, the loop runs
forever and crashes your program. Always ensure your loop will eventually end.