While Loop

JavaScript while loop loops through a block of code while a specified condition is true.

Syntax

while (condition) {
    // code block to be executed
}

While-loop header begins with keyword while, then a condition enclosed in parentheses. Loop body is indented and enclosed in {}.

In the following example, the code in the loop will run over and over again, as long as a variable i is less than 5:

Example

// while5

let i = 0;
while (i < 5) {                
    console.log( 'i: ' + i );      
    i++;               
}                                 
console.log('Out of the while block')

Run and see the console result:

i: 0              
i: 1
i: 2
i: 3
i: 4
Out of the while block

Here are the logic steps the computer follows when executing a while loop:

  1. Check the condition, i < 5, and evaluate whether it is true or false. If it's false, exit the loop

  2. If the condition is true, execute the code in the block.

  3. After finishing all the code in the loop body, go back to the beginning of the loop and repeat from step 1.

results matching ""

    No results matching ""