Lesson 10 - Do-While Loop in JavaScript
A do-while loop is similar to the while loop, but it executes the instructions once before checking for the condition it's supposed to obey. So, it's like I say "keep learning while I am arround". Then you start learn, and then you realize I was not around. But, as far as, I am, you will continue learning.
So lte's see how to implement the do-whille in Javascript.
let number = 0;
do {
console.log("Number is: " + number);
number++;
} while (number < 5);
Explanation:
- A
do-while
loop is similar to awhile
loop but guarantees at least one execution before checking the condition. - The loop runs the block of code once, then checks
if number < 5
to determine whether to continue. - This is useful when you need to execute something at least once, regardless of the condition.
A great example of third point is when we need to show an application menu and give the user the opportunity to select what to do.
const option = 3;
do {
console.log('SELECT OPTION:');
console.log(" 0 - Menu ");
console.log(" 1 - Orders ");
console.log(" 2 - Products ");
console.log(" 3 - Exit ");
//...
}while(option != 3);
Try your hand:
1. Create a File
Create a new file namedlesson10-do-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 10 - Do-While Loop</title>
</head>
<body>
<script>
let number = 0;
do {
console.log("Number is: " + number);
number++;
} while (number < 5);
</script>
</body>
</html>
Save the file in your folder.
3. Preview the File:
- Open the file in your browser and access the developer console.
- Observe the output:
Number is: 0
Number is: 1
Number is: 2
Number is: 3
Number is: 4
4. Experiment:
- Change
number = 10
and refresh the browser. - What happens? The loop still runs once before checking
while (number < 5)
, proving the do-while behavior. - Change the condition from
number < 5
tonumber < 10
and observe how the loop behaves.