Tutorials

Learn web design and programming with our free video and text tutorials.

Web Designer? Design and market your own professional website with easy-to-use tools.

Javascript while Loops Tutorial

Javascript allows you to use loops to execute the same block of code a specified number of times while a condition is true.

In javascript there are two different kind of loops: for loops and while loops

The while loop is used to execute a statement and to continue executing the statement while the specified condition is true.

The javascript code below shows you the while loop in action.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>WebDevelopmentTutorials.com</title>

</head>
<body>

<script type="text/javascript" language="javascript">

count = 1;
while (count<=10)
{
document.write("I can count to " + count + "<br />");
count++;
}

</script>

</body>
</html>

The javascript code above displays:

The do...while loop is a variation of the while loop. It executes a block of code at least once, even if the specified condition is false, it will then repeat the loop as long as the specified condition is true.

The javascript code below shows you the do...while function in action.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>WebDevelopmentTutorials.com</title>

</head>
<body>

<script type="text/javascript" language="javascript">

var i=10;
do
{
document.write("The number is " + i);
document.write("<br />");
i=i--;
}
while (i<0);

</script>

</body>
</html>

The javascript code above displays: