JavaScript while loop

while loop

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

Syntax

while (condition)
{
Code to be executed
}

Example

The loop in this example will continue to run as long as variable i is less than 10:

    php中文网(php.cn) 

点击下面的按钮,只要 i 小于 5 就一直循环代码块。

Note: If you forget to increment the value of the variable used in the condition, the loop will never end. This may cause the browser to crash.

Run the program and try it


##do/while loop

The do/while loop is a variation of the while loop body. The loop executes the block of code once before checking whether the condition is true, and then repeats the loop if the condition is true.

Syntax

do

{
Code to be executed
}
while (condition );

Example

The following example uses a do/while loop. The loop will execute at least once, and it will execute even if the condition is false, because the code block will execute before the condition is tested:

    php中文网(php.cn) 

点击下面的按钮,只要 i 小于 5 就一直循环代码块。

Run the program to try it



Continuing Learning
||
php中文网(php.cn)

点击下面的按钮,只要 i 小于 10 就一直循环代码块。

submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!