# Logical Structures (Conditionals and Loops)

### Logical Structures (Conditionals and Loops )

Logical structures allow us to determine whether certain statements are going to execute, and how many times they'll execute. The two most commonly used kinds of logical structures are if-then statements and for-loops . Other kinds of logical structures, not covered here, include switch statements, while-loops, and do-loops.

#### Conditional Statements

A conditional statement evaluates a specified condition and determines which other statements to execute based on whether the condition evaluates as true or false. These are also sometimes called if-then statements. The basic syntax for a conditional can be one of the following:

` if (condition) {  statements to execute;  }  or  if (condition) {  statements to execute;  } else {  other statements to execute;  } `

Conditional statements use conditional operators to evaluate whether a condition is true or false. These include:

` == is equal to  => is equal to or greater than  >  is greater than  =< is equal to or less than  <  is less than  != is not equal to `

If more than one condition must be evaluated to determine whether a set of code statements should be executed, Boolean operators are used to combine the expressions. These include:

 && both conditions must be true one of the conditions must be true &! one of the conditions must be true; the other must be false

Here is a sample function that will bring up an alert window only if two conditions are metone variable must be larger than 10, and another must be equal to 6.

` function addMe(a,b) {  var c = a + b;  if (c >10 && a == 6) {     alert("The sum of these numbers is " + c + ".");     }  } `

The indented lines here are simply to make the code more readable by us humans . It doesn't affect how the JavaScript interpreter treats the statements.

#### Practice Session #4

In this exercise, you'll build on the practice file you've been creating. You'll add a conditional statement to govern what message appears in the alert window.

1. Open the practice3.htm file. Save it as practice4.htm.

2. To test the basic workings of conditionals, revise the main function so that it contains an if-then statement that always evaluates to true (new code is in bold):

` <script language="JavaScript">  function greetMe(person,salutation) {  if (true) {  var greeting = salutation + ", " + person + "!";     alert(greeting);  }  }  </script> `
3. Save the file and try viewing it in a browser. Because the conditional is always true, the greeting window will always appear.

4. Change the condition so that it is always false:

` <script language="JavaScript">  function greetMe(person,salutation) {  if (  false  ) {     var greeting = salutation + ", " + person + "!";     alert(greeting);     }  }  </script> `
5. Save the file and try viewing it in a browser again. Because the conditional is always false, no greeting will ever appear.

6. Now rewrite the statement so that it tests one of the variables and executes (or not) based on that (new code is in bold):

` <script language="JavaScript">  function greetMe(person,salutation) {  if (  person == "Fred"  ) {     var greeting = salutation + ", " + person + "!";     alert(greeting);     }  }  </script> `
7. Save again and preview in a browser. If you click on the first link in your page (the one that passes "Fred" as a parameter), the alert will appear. If you click on the second link (the one that passes "Barney" as a parameter), no alert will appear.

8. Now add an else clause to your if-then statement so that alternate code will be executed if the condition is false (new code is in bold):

` <script language="JavaScript">  function greetMe(person,salutation) {  if (person == "Fred") {     var greeting = salutation + ", " + person + "!";     alert(greeting);     }  else {   alert("You aren't Fred!");   }  }  </script> `
9. Try this in a browser. Clicking on the second link should cause the message "You aren't Fred!" to appear in the alert window. Clicking on the first link causes the original greeting to appear.

#### For-Loops and Arrays

Loop statements specify that certain other code statements, those contained within the loop, should be executed a certain number of times. The syntax for a for-loop looks like this:

` for (var a=0; a < 10; a++) {  [statements to be executed]  } `
The opening statement of the for-loop does the following:
• Creates a counter variable and assigns that variable a starting value

• Specifies an ending condition, when the counting variable reaches a certain number

• Increments the counting variable

The JavaScript interpreter will execute the statements enclosed within the loop over and over, incrementing the counting variable each time, until the counting variable reaches the ending condition. Then the loop will stop.

Loop statements are often used in conjunction with arrays. An array is a special kind of variable that, instead of holding a single value, holds a series of values. Arrays are created like this:

` var myArray = new Array(); `

The individual slots in an array can be filled with values by referring to them by number:

` myArray[0] = 16;  myArray[1] = 7;  myArray[2] = 23; `

Note that the numbering always begins with 0. To refer to an individual value within the array, the array name and slot number are used together, like this:

` var x = myArray[0] + myArray[2]; `

To find out how many slots an array has, access its length property:

` var x = myArray.length; `

#### Practice Session #5

In this exercise, you'll use an array to hold a series of names. Then you'll use a loop to access all the names in the array, adding each to the final greeting to be displayed in the alert window.

1. In your text editor, create a new file. Enter the basic HTML code framework, unless your editor has done so for you. Save the file as practice5.htm.

2. Enter the framework code for a function called listNames() in the document <head> . The code for your <head> section should look like this:

` <head>  <title>Practice Session 5</title>  <script language="JavaScript">  function listNames() {  }  </script>  </head> `
3. Enter a function call for this function in the document <body> . The code for your <body> section should look like this:

` <body>  <a href="#" onClick = "listNames()">Click here for a list of names.</a>  </body> `
4. In your function, create an array and populate it (fill its slots) with four names (new code is in bold):

` function listNames() {  var myNames = new Array();   myNames[0] = "Fred";   myNames[1] = "Barney";   myNames[2] = "Wilma";   myNames[3] = "Betty";  } `
5. Now create an alert message that displays the contents of a variable called list (new code is in bold):

` function listNames() {  var myNames = new Array();  var myList = "";  myNames[0] = "Fred";  myNames[1] = "Barney";  myNames[2] = "Wilma";  myNames[3] = "Betty";  alert(myList);  } `

Note that the myList variable starts out as an empty string, indicated by two quote marks side-by-side.

6. Finally, add the for-loop that will create a display list from the members of the array (new code is in bold):

` function listNames() {  var myNames = new Array();  var list = "";  myNames[0] = "Fred";  myNames[1] = "Barney";  myNames[2] = "Wilma";  myNames[3] = "Betty";  for (var a=0;a<myNames.length;a++) {   list+=myNames[a]+"\n";   }  alert(list);  } `

This loop starts with the counting variable a equal to . It adds the value stored in myNames[0] to the list, followed by a new line character ( \n ). Then it keeps adding 1 to the counting variable and collecting the value from the next slot in the array, until it comes to the end of the array.

7. Save the page and try it out in a browser! If your syntax has been correct throughout, clicking the text link will call the listNames() function and generate an alert window like that shown in Figure A.6.

##### Figure A.6. The practice5.htm file, showing an alert window generated by looping through the values stored in an array.

Dreamweaver MX Extensions
ISBN: 0735711828
EAN: 2147483647
Year: 2001
Pages: 141
Authors: Laura Gutman

Similar book on Amazon