The javascript conditional while statement is also called a loop statement. A while statement is given a specific condition and while it is met it will run code within the block of the statement.

First of all a html5 page is created with ‘script’ tags on line 8.

In between the script tags on line 9 a variable named ‘i‘ is made and initialised with a value of ‘0‘.

In the next code snippet below on line 10 a while statement is added inside the script tags. The variable ‘i’ is used to set a condition. The condition reads ‘(i < 5)'. This means the while statement will run while the variable 'i' has a value that is less than the value of 5. As 'i' has a value of '0' the while statement will run. In addition on line 11 the 'document.write(i)' command will write the value of 'i' into the html5 document. To avoid a never ending occurrence of the while statement running the value of 'i' needs to change so that eventually it will reach a value of '5' or above. While 'i' is greater that 4 or not less than 5 the while statement will not run. The 'i++' statement on line 12 will increase the value of 'i' each time the while statement runs.

Javascript Conditional While Statement. 1,2,3,4.

The value of ‘i’ has been written in the document each time the while statement runs. The value of ‘i’ increased each loop through until it failed the condition of having a value less than 5.

Below on line 11 inside the ‘document.write’ property some formatting of the output has been added.

Javascript Conditional While Statement. 1,2,3 and 4 on a new line.
The ‘i’ value is written to the html5 document while it has a value less than 4.

Now on line 10 the condition reads ‘(i < 10 )‘ to emphasise how a javascript conditional while statement works.

Javascript Conditional While Statement. 0 to 9  in a vertical row.
The while statement has now run 10 times as the condition set is that while the value of ‘i’ is less than ’10’.

More on Javascript

Javascript logo.

Share!Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPin on PinterestShare on RedditShare on Tumblr

Leave a Reply

Your email address will not be published. Required fields are marked *