Javascript Loops

JavaScript supports different kinds of loops:

  • for- loops through a block of code a number of times
  • for/in- loops through the properties of an object
  • while- loops through a block of code while a specified condition is true
  • do/while- also loops through a block of code while a specified condition is true

The for loop

The for statement creates a loop with 3 optional expressions:

for (expression 1; expression 2; expression 3) {
  // code block to be executed
}

Example

<!DOCTYPE html>
<html>
<head>
<title>HTML Tutorials</title>
</head>
<body>
<h2>JavaScript For Loop</h2>
<p id="loop"></p>

<script>
var text = "";

for (var i = 0; i < 5; i++) {
  text += "The number is " + i + "<br>";
}

document.getElementById("loop").innerHTML = text;
</script>

</body>
</html>


The for in loop

The JavaScript for in statement loops through the properties of an Object:

Syntax

for (key in object)
{

//code to be executed

}

Example


<!DOCTYPE html>
<html>
<head>
<title>HTML Tutorials</title>
</head>
<body>

<p id="forin"></p>

<script>
var person = {
fname:"Prasanjeet",
 lname:"Ghosh",
 age:31
 }; 

var txt = "";
for (var x in person) {
  txt += person[x] + " ";
}

document.getElementById("forin").innerHTML = txt;
</script>

</body>
</html>






While loop

The condition is first evaluated. If true, the block of statements following the while statement is executed. This is repeated until the condition becomes false. This is known as a pre-test loop because the condition is evaluated before the block is executed.



Do -While loop

Next is an example of a JavaScript do while loop:





No comments:

Post a Comment