codescracker


javascript

JavaScript do-while Loop



« Previous Tutorial Next Tutorial »


The do-while loop in JavaScript is used in the case where you want a group of statements to be executed at least once.

Since the condition is placed at the end of the loop in case of do-while loop in JavaScript, therefore you can use this loop to executed group of statements at least once.

Here is the general form of do-while loop in JavaScript:

do {
	// block of code to be executed here
	// incrementation
} while(condition);

JavaScript do-while Loop Example

Here is an example illustrates how to use do-while loop in JavaScript:

<!DOCTYPE HTML>
<html>
<head>
	<title>JavaScript do-while Loop</title>
</head>
<body>

<h3>JavaScript do-while Loop Example</h3>
<script type="text/javascript">
	
	var num = 2;
	document.write("Printing the table of " + num + "<br/>");
	var i = 1;
	do
	{
		document.write(num*i + "<br/>");
		i++;
	} while(i<=10);
	document.write("Done!");
	
</script>

</body>
</html>

Here is the sample output of the above JavaScript do-while loop example:

javascript do-while loop

Here is another example of do-while in JavaScript. This example shows you the difference between while and do-while loop.

<!DOCTYPE HTML>
<html>
<head>
	<title>JavaScript do-while Loop</title>
</head>
<body>

<h3>JavaScript do-while Loop Example</h3>
<script type="text/javascript">
	
	var num = 2;
	document.write("Printing the table of " + num + "<br/>");
	var i = 1;
	do
	{
		document.write(num*i + "<br/>");
		i++;
	} while(i>10);
	document.write("Done!");
	
</script>

</body>
</html>

Here is the sample output of the above do-while loop in JavaScript example:

javascript do-while loop example

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test