LOOPING IN JAVASCRIPT

LOOPING:

LOOP: When a block of code is executed several number of times then  it’s referred as a Loop.
Types: JavaScript supports
1.      While
2.      Do…..while
3.      For
While :
Syntax:
while (expression){
   Statement(s) to be executed if expression is true
}
Description:
The purpose of a while loop is to execute a statement or code block repeatedly as long as expression is true. Once expression becomes false, the loop will be exited.
Example:
while (count < 10){
  document.write("Current Count : " + count + "<br />");
  count++;
}

Do…While:

Syntax:
do{
   Statement(s) to be executed;
} while (expression);

Description:
The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false.
Example:
do{
  document.write("Current Count : " + count + "<br />");
  count++;
}while (count < 0);

For:

Syntax:
for (initialization; test condition; iteration statement){
     Statement(s) to be executed if test condition is true
}

Description:
The for loop is the most common and compact form of looping and includes the following three important parts:
·         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.
We can put all the three parts in a single line separated by a semicolon.
Example:
for(count = 0; count < 10; count++){
  document.write("Current Count : " + count );
  document.write("<br />");
}


For…in:

Syntax:
for (variablename in object){
  statement or block to execute
}

Description:
  • This loop is used to loop through an object's properties.
  • In each iteration one property from object is assigned to variablename and this loop continues till all the properties of the object are exhausted.
Example:
<script type="text/javascript">
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator)
{
  document.write(aProperty);
  document.write("<br />");
}
document.write("Exiting from the loop!");
 
</script>
Output:
 
Navigator Object Properties
appCodeName
appName
appMinorVersion
cpuClass
platform
plugins
opsProfile
userProfile
systemLanguage
userLanguage
appVersion
userAgent
onLine
cookieEnabled
mimeTypes
Exiting from the loop! 
 

REFERENCE FROM: 1. http://www.tutorialspoint.com/javascript

No comments:

Post a Comment