Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript while Loop

JavaScript while Loop


A loop can keep executing a block of code as long as a specified condition is true.


while loop

A while loop executes a block of code while a specified condition is true.

Syntax

while (

Conditional

)

{

    code to be executed

}

Example

The loop in this example will keep running as long as the variable i is less than 5:

Example

while

(

i

<

5

)

{

x

=

x

"

The number is

"

i

"


"

;

i

++;

}

Try it »

lamp If you forget to increase the value of the variable used in the condition, the loop will never end. This may crash the browser.

The do/while Loop

The do/while loop is a variant of the while loop. This loop executes a 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 (

Conditional

);

Example

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

Example

do

{

x

=

x

"

The number is

"

i

"


"

;

i

++;

}

while

(

i

<

5

)

;

Try it »

Do not forget to increase the value of the variable used in the condition, otherwise the loop will never end!


Comparing for and while

If you have read the previous chapter about for loops, you will find that a while loop is very similar to a for loop.

The loop in this example uses for loopto display all the values in the cars array:

Example

cars

=

[

"

BMW

"

,

"

Volvo

"

,

"

Saab

"

,

"

Ford

"

]

;

var

i

=

0

;

for

(

;

cars

[

i

]

;

)

{

document

.

write

(

cars

[

i

]

"


"

)

;

i

++;

}

Try it »

The loop in this example uses while loopto display all the values in the cars array:

Example

cars

=

[

"

BMW

"

,

"

Volvo

"

,

"

Saab

"

,

"

Ford

"

]

;

var

i

=

0

;

while

(

cars

[

i

]

)

{

document

.

write

(

cars

[

i

]

"


"

)

;

i

++;

}

Try it »