Monday, 18 April 2016

Javascript Loops


The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops. It makes the code compact. It is mostly used in array.

That means,
Instead of writing,
val+= name[0] + "
"
;
val+= name[1] + "
"
;
val+= name[2] + "
"
;

you can use
for (i = 0; i < name.length; i++) {
    val+= name[i] + "
"
;
}

Different Kinds of 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

1) JavaScript For loop: 

The JavaScript for loop iterates the elements for the fixed number of times. It should be used if number of iteration is known.

syntax:
for (initialization; condition; increment)
{
    code to be executed
}  

example:
for (i = 0; i < 5; i++) {
    val+= "The value is " + i + "
"
;
}

2)The For/In Loop

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

example:
var name= {fname:"Ravi", lname:"k"umar, age:25};
var val= "";
var x;
for (x in person) {
    val+= name[x];
}

3) JavaScript while loop

The JavaScript while loop iterates the elements for the infinite number of times. It should be used if number of iteration is not known. 
syntax:
while (condition)
{
    code to be executed
}  
example:
<script>
var i=10;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>

4) JavaScript do while loop

The JavaScript do while loop iterates the elements for the infinite number of times like while loop. But, code is executed at least once whether condition is true or false. 
syntax:
do{
    code to be executed
}while (condition);  

example:
<script>
var i=20;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>

No comments :

Post a comment