Lesson 9 - The wile loop
**The while loop, like the previous [foo]() loop, we saw is also used to control the flow of your program**.
Just like in plain English you would say: "While I am dressing, get your self some food and be eating". So, the other person will have to stop eating as soon as you are done dressing. Inversely, as long as you continue to dress, they will continue to eat. That's the core principle of that while loop. It has a condition, if that condition is satisfied, we do the work, and then adjust the condition.
Now let's see how to use the while in JavaScript.
let count = 0;
while (count < 5) {
console.log("Count is: " + count);
count++;
}
Explanation:
- A while loop runs as long as the condition remains
true
. - Here, count starts at
0
and increases by1
each time the loop runs. - The loop stops when
count
reaches5
.
Try your hand
1. Create a file
Create a new file named lesson9-while-loop.html
.
2. Write the Code
Copy and paste the following code into your file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Day 9 - While Loop</title>
</head>
<body>
<script>
let count = 0;
while (count < 5) {
console.log("Count is: " + count);
count++;
}
</script>
</body>
</html>
Save the file in your folder.
Preview the File
- Open the file in your browser and access the developer console.
- Observe the output:
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Note: The count started from zero to 4. The idea is we count 5 time, not up to 5.
Experiment
- Change
while (count < 5)
towhile (count < 10)
and refresh the page to see more iterations. - Try an infinite loop (use with caution!)
while (true) {
console.log("You and I will be together forever!");
}
- To stop the infinite loop, close the browser tab or use
Ctrl + C
in a terminal.