JavaScript Do-While Loop
About JavaScript Do-While Loop
In JavaScript, do-while loop is a control flow statement that executes a block of code first and then evaluates the condition. It repeatedly executes the block as long as a specified condition is true.
The condition must be a Boolean expression that evaluates to true or false.
In do-while loop, the condition must eventually become false. Otherwise, the loop will run indefinitely.
It is important that the condition changes within the loop's body and eventually becomes false.
Syntax of 'Do-While' Statement
The general syntax of 'do-while' statement is as follows:
Components of do-while Loop
- do: The 'do' keyword starts the do-while loop.
- Code Block: The block of code will be executed once before checking the condition.
-
Condition Update: The condition must be updated to make it eventually
false. Otherwise, the loop will run indefinitely. - while(condition): The 'while' is the keyword. The 'condition' is passed as a Boolean expression. The loop repeatedly executes a block of code as long as the specified condition is true. If the condition is false, the loop will stop and move to the next program flow.
Create 'Do-While' Loop Statement
In the following example, a do-while loop statement is created that prints numbers from 1 to 5.
Example of 'do-while' Loop Statement
Output of the above example
1
2
3
4
5
Explanation of the code
-
do: The 'do' keyword starts the do-while loop. -
let num = 1;: This line declares a variable named 'num' and assigns number1. -
console.log(num);: The block of code executes once before checking the condition. -
num++;: It updates(increments) the value of 'num' variable by 1 at each iteration. If the 'num' value is not updated, the loop will run indefinitely. -
while(num <= 5): The 'while' is the keyword andnum <= 5is the condition. As long as, the value of 'num' variable is less than or equal to 5, the loop will repeatedly execute the block of code inside the curly braces '{}' under 'do' statement.
JavaScript Compiler For Live Practice
Practice the above JavaScript code in the following JavaScript editor. Create more JavaScript 'do-while' loop statements in the following editor and click Execute button to check the output. The output will be displayed in JavaScript Code Output section.
JavaScript Compiler