Loops in JavaScript

by George Freedrich.

Share
|
Homepage | Submit your article | Contact | TOS
More articles on ajax and javascript  

You are here: Categories » Computers and technology » AJAX and JavaScript

Loops in JavaScript are similar to loops in C++ and Java and most other languages using loop structures. In this section, you will find explanations of the different types of loops in JavaScript and suggestions where they are typically used most effectively in a script.

The for Loop

One of the most used and familiar loops is the for loop. This loop iterates through a sequence of statements for a number of times determined by a condition. The condition can be a constant based on a numeric literal (a number) or a constant (that is, a math constant), or the loop can be variable depending on the count in the variable. The general format is shown here:

for(start value; termination condition; increment/decrement) {
      Statements 
      } 

The start value is the initial value of a counter variable. The first time through the loop, the counter value will be based on the start value. The termination condition is a test to determine whether the counter variable has met the condition that terminates the loop. The increment/decrement determines how much has been added or subtracted from the counter variable. A typical use for a loop is to examine characters in a string. The length of the string is used as the termination condition, and each character is based on its linear position in the string.

<html> 
<head> 
<title>For Loop</title> 
<script language="JavaScript"> 
var found = "Email address is missing @ symbol."; 
var emailAd=prompt("Please enter your email address:",""); 
for (var counter=0; counter <= emailAd.length; counter++) {
//The charAt(n) function looks at the character 'n' in the string 
            var findAt=emailAd.charAt(counter); 
                  if (findAt=="@") {
                              found="Email address has @ symbol"; 
                  } 
} 
document.write(found); 
</script> 
</head> 
<body bgColor="powderblue"> 
</body> 
</html>

Because the length of the string is a variable, the termination condition uses the length of the string rather than a literal value. In this particular example, all that the script is attempting to do is verify whether the user remembered to put in the "@" when she entered her email address.

The for/in Loop

A second format used with the for keyword in a loop is the for / in statement. When the for / in statement is used, the counter and termination are determined by the length of the object. The general format is shown here:

for (counter variable in object) {
      Statement 
} 

You do not need to know the number of properties in the object using for / in because the statement begins with 0 as the initial value of a counter variable and terminates the loop when all of the properties of the objects have been exhausted. For example, using an array object, the following loop begins with the first element of the array named airplane and keeps looping until no more elements are found in the array:

<html> 
<head> 
<title>For Loop</title> 
<script language="JavaScript"> 
var airFlock=""; 
var airplane = new Array("Cessna","Piper","Maule","Mooney","Boeing"); 
for (var counter in airplane) {
      airFlock += airplane[counter] + "<br>"; 
} 
document.write(airFlock); 
</script> 
</head> 
<body bgColor="powderblue"> 
</body> 
</html>

Because variables are objects in JavaScript, each character of a string variable is a property of the variable. Rewriting the script used to illustrate how a for loop works, the following for / in loop requires a simpler statement to arrive at the same results:

<html> 
<head> 
<title>Search For/In</title> 
<script language="JavaScript"> 
var complete="You are missing the @ character in your email address."; 
var emailAd = prompt("Enter your email address",""); 
for (var counter in emailAd) {
      if (emailAd[counter]=="@") {
            complete="You included your @ character."; 
      } 
} 
document.write(complete); 
</script> 
</head> 
<body bgColor="aliceblue"> 
</body> 
</html>

Using the for / in loop in simple strings is just as effective as its use in other objects that contain properties.

The while Loop

The while loop begins with a termination condition and keeps looping until the termination condition is met. The counter variable initialization and the counter increment/decrement are handled within the context of the while statement (that is, within the curly braces), but they are not part of the initial statement itself. The general format for the while loop is shown here:

initial value declaration 
while (termination condition) {
      statements 
      increment/decrement statement 
} 

As long as the termination condition is not met, the statements are executed and the counter variable increases or decreases in value. The following example illustrates the counter variable decrementing in steps of 5:

<html> 
<head> 
<title>While Loop</title> 
<script language="JavaScript"> 
var counter = 50; 
var teamGroups=""; 
while(counter > 0) {
      teamGroups +="Team " + counter + "<br>"; 
      counter -= 5; 
} 
document.write(teamGroups); 
</script> 
</head> 
<body bgColor="teal"> 
</body> 
</html>

The output to the screen is as shown:

Team 50 
Team 45 
Team 40 
Team 35 
Team 30 
Team 25 
Team 20 
Team 15 
Team 10 
Team 5

The fact that no Team 0 exists is important. As soon as the termination condition returned a Boolean false, the loop was immediately terminated and the script jumped over the statements within the loop and executed the next line. Had the termination condition been this, a Team 0 would have been included in the output:

while(counter >= 0) {

The do/while Loop

Unlike the while loop, the do / while loop always executes statements in the loop in the first iteration of the loop. Instead of the termination condition being at the top of the loop, it is at the bottom. The general format looks like the following:

do {
        statements 
        counter increment/decrement 
} while(termination condition) 

The keyword while is outside the curly braces beginning after the do keyword. Because arrays are commonly used with loops, the following shows a do / while loop extracting the properties of an array:

<html> 
<head> 
<title>Do/While Loop</title> 
<script language="JavaScript"> 
var bigCities= new Array("Beijing", "Tokyo", "Mexico City", "New York", "Los 
Angeles", "London", "Berlin", "Bloomfield") 
var counter=0; 
var metropolis=""; 
bigCities.sort( ); 
do {
      metropolis += bigCities[counter] + "<br>"; 
      counter++ 
} while (counter < bigCities.length) 
document.write(metropolis); 
</script> 
</head> 
<body bgColor="cornsilk"> 
</body> 
</html>

The sorting statement, bigCities.sort( ), puts the array elements into alphabetical order before the array is placed in the loop. Then the loop iterates until the counter variable returns a Boolean false based on the length of the array. Because the elements have been arranged alphabetically, the output is arranged alphabetically, as the following shows:

Beijing 
Berlin 
Bloomfield 
London 
Los Angeles 
Mexico City 
New York 
Tokyo

Leave a comment or ask a question
Total comments: 0

AJAX and JavaScript Disclaimer

  • The e-articles directory is not responsible for any and all copyright infringements by writers and authors. If you suspect the information contained by this page for any copyright infringements, please contact us to investigate the issue
What Is Ajax - Ajax stands for Asynchronous Javascript And XML. Although strictly speaking Ajax itself is not a technology, it mixes well-known programming techniques in an uncommon way to enable web develo (more...)
JavaScript as a Primary Development Language for AJAX applications - JavaScript is a powerful scripting language, but deserved or undeserved, it has gained a bad reputation. If you take some time to look at JavaScript with a fresh eye, you will notice that most (more...)
Promises and Problems of Combining AJAX with Other New Technologies - As you work with AJAX, you may hear of related technologies that you can use with AJAX. They fit into two main groups: mature technologies that are widely available in many browsers today, and (more...)
XMLHttpRequest Overview - Originally, Microsoft designed XMLHttpRequest to allow Internet Explorer (IE) to load XML documents from JavaScript. Even though it has XML in its name, XMLHttpRequest really is a generic HTTP (more...)
Goals of AJAX - First and foremost, AJAX is about improving user experience; user experience improvements fall into two categories: making current tasks easier and making previously impossible tasks possible. (more...)
JavaScript Lives in a Web Page - All the code that you write for JavaScript goes into an HTML page. If you don't know HTML yet, you should run out and get a good book on HTML. Lynda and William Weinman's (more...)
JavaScript Literals - The raw data that make up the root of data types are called "literals." These are, in effect, literally what they represent themselves to be. Numbers, strings, and Boolean values make up the cor (more...)
JavaScript Variables - I like to think of variables as containers on a container ship. You can put all different types of content into the containers, move them to another port, empty them, and then replace the contain (more...)
JavaScript Operators - Operators can be placed into three categories-binary, unary, and ternary. Binary operators, most commonly associated with the concept of operator, take two (binary) expressions and combine them in (more...)
JavaScript Arrays - Because objects are collections of properties with each property having its own name and value, arrays are actually JavaScript objects. Each property in an array is an element, and each element (more...)

 
free content
    Copyright © 2006 - 2012 e-articles.info.
The texts, articles and tutorials in the directory are property of their respective owners and authors.