JavaScript while Loop
The JS while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.
Syntax
while (boolean condition) {
loop statements...
}
Flowchart
- While loop starts with checking the condition. If it is evaluated to be true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason, it is also called the Entry control loop
- Once the condition is evaluated to be true, the statements in the loop body are executed. Normally the statements contain an updated value for the variable being processed for the next iteration.
- When the condition becomes false, the loop terminates which marks the end of its life cycle.
Example
// JavaScript code to use while loop
let val = 1;
while (val < 6) {
console.log(val);
val += 1;
}
Output
1 2 3 4 5
JavaScript Loops
JavaScript loops are essential for efficiently handling repetitive tasks. They execute a block of code repeatedly as long as a specified condition remains true. These loops are powerful tools for automating tasks and streamlining your code.
For example, suppose we want to print “Hello World” 5 times. This can be done using JS Loop easily. In Loop, the statement needs to be written only once and the loop will be executed 5 times as shown below:
for (let i = 0; i < 5; i++) {
console.log("Hello World!");
}
Output
Hello World! Hello World! Hello World! Hello World! Hello World!
Table of Content
- for Loop
- while Loop
- do-while Loop
- for-in Loop
- for-of Loop
- Labeled Statement
- Break Statement
- Continue Statement
- Infinite Loop (Loop Error)