The for loop is the most compact form of looping and includes the following three important parts:
You can put all the three parts in a single line separated by a semicolon.
Syntax:
for (initialization; test condition; iteration statement){
Statement(s) to be executed if test condition is true
}
Example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Siple Javascript conditions</title>
</head>
<body>
<button onclick="myLoop()">Click Me</button>
<script>
function myLoop()
{
var count;
for(count=1;count <=10; count++)
{
document.write("Number: "+count+"<br/>");
}
}
</script>
</body>
</html>
- The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
- The test statement which will test if the given condition is true or not. If condition is true then code given inside the loop will be executed otherwise loop will come out.
- The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by a semicolon.
Syntax:
for (initialization; test condition; iteration statement){
Statement(s) to be executed if test condition is true
}
Example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Siple Javascript conditions</title>
</head>
<body>
<button onclick="myLoop()">Click Me</button>
<script>
function myLoop()
{
var count;
for(count=1;count <=10; count++)
{
document.write("Number: "+count+"<br/>");
}
}
</script>
</body>
</html>
Comments
Post a Comment