LIS 390W1A - Lab 16: Loops & Conditionals

Legend

 
= Javascript
 
= PHP

Javascript Start

Everyone should check out these JavaScript tutorials at Quirksmode.

To begin, let's bring back some of the functions and data structures we created last time. The data structures will be more fully fleshed out this time.

Javascript if { }

The if statement is the primary way which to encode decision making in computer programs. There are other statements which can make decisions (the switch statement, for example), but they are simply shorthand for using multiple if statements. Logically, they act in the same manner as the if statement.

if (condition) {
	// execute when condition is true
	}
	

The "condition" in the if statement must be something whose value is either "true" or "false". Because javascript is a weakly-typed language (as we discussed last time), false=0, and true=anything else (this tends to be the case for most weakly typed languages). Thus, even a string will be interpreted as being "true" (see the str='0'; example below). If the condition is true, then the code within the statement executes. If it is false, then the code will not execute.

For example:

Notice that most of the conditionals above use comparison operators. Most of these are pretty straightforward, but here's a table of reference:

Table of javascript comparison operators
Operator Effect
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to (note, this does not mean set equal to, which is the single equal sign)
=== identical to (this is useful for strict comparisons, i.e., in cases when you want to take advantage of strong types: ('1' == 1) returns true, whereas ('1' === 1) returns false.)
!= not equal to

Of course, if the condition in the if statement is false, then the code within the if statement will not execute. For example:

Notice, there is no output above this text, because the conditionals are all false.

Sometimes you will want to create if statements that are more complex than what is above, where you will make multiple comparisons. To do so, you will need to chain conditions together using Boolean operators. Boolean operators correspond exactly to their logical (math, philosophy) equivalents, and, in fact, are also how the processing gates inside the computer are setup to work. Here is a table that summarized the Boolean operators:

Table of Boolean operators
Operator Effect Form Description
&& and (x && y) The condition is true only if both inputs are true, otherwise it is false.
|| or (x || y) The condition is true as long as one of the inputs is true; if both inputs are false, then it is false.
! not (!x) Flips or toggles the value of the input from true to false or false to true.

For example:

Notice, that last example's a bit tricky. The nots modify the variables, not the conditional statements. Thus, given that javascript is weakly typed, the varibles flip between 0 and not-0. Any true state that is created is automatically given a value of 1. Thus:

For more information see the W3Schools comparison and boolean operator page.

Javascript if { } else { }

It is often desirable to create an if statement where if the condition is not met, then a different chunk of code should be executed. The if...else statement provides just such functionality.

if (condition) {
	// execute when condition is true
	} 
	else 
	{
	// execute when condition is false
	}
	

For example:

Javascript if { } else if { } else { }

Sometimes, there are multiple conditions you might want to check for. The if ... else if ... else statement does this.

if (condition) {
	// execute when condition is true
	}
	else if (other condition) 
	{
	// execute when first condition is false and second condition is true
	}
	else 
	{
	// execute when neither condition is true
	}
	

You can have as many else if's as you need. For example:

One thing to be careful of, is that when you use if...else if statements, only the first match executes. Thus:

Here, the first condition (x > 1) is the only condition that is executed. Even though the (x == 5) condition would be true for this example, the code will not be executed, and thus the text "x is equal to five" will not be displayed.

Javascript switch Statement

Typing out a large number of conditions in an if ... elseif... statement can quickly become a pain, which is why the switch statement was developed. The basic form of the switch statement is as follows (I am using the arrays defined above):

Notice how since "Jin Ha" is not one of the cases, the default option is selected. When "Sarah" or "Cameron" is the person, then the appropriate case is selected, and the switch statement ends. However, when "Ingbert" is the peron, then the switch statement selects the right case, but because there is no break statement, the switch keeps operating, executing printVar both in case "Ingbert" and in case "Cameron".

PHP Conditionals

The statements we have just covered, if ... elseif ... else and switch statements, are statements known as conditionals, because they involve executing code only if certain conditions apply. PHP has these conditionals as well.

<?php

if ($x == 0) 
{
	echo "<p>x equals 0</p>";
} 
elseif ($x == 1) 
{
	echo "<p>x equals 1</p>";
} 
elseif ($x == 2) 
{
	echo "<p>x equals 2</p>";
}
else
{
	echo "<p>x is not equal to 0, 1, or 2</p>";
}

switch ($x) {
case 0:
	echo "<p>x equals 0</p>";
	break;
case 1:
	echo "<p>x equals 1</p>";
	break;
case 2:
	echo "<p>x equals 2</p>";
	break;
case 3:
	echo "<p>x equals 3</p>";
default:
	echo "<p>x is not equal to 0, 1, or 2</p>";
}

?>
	

PHP also has comparison and boolean operators, which are largely similar to javascript's operators. (Click here to see all the different kinds of operators in PHP.)

Table of PHP comparison operators
Operator Effect
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to (note, this does not mean set equal to, which is the single equal sign)
=== identical to, a.k.a. strictly equal to (as with javascript, this means that the match has to be exact, and should be used if you are trying to do strong typing; click here for more details on the difference between loose and strict comparisons)
!= not equal to
<> not equal to (this performs the same operation as !=)
!== not identical to
Table of PHP Boolean (logical) operators
Operator Effect Form Description
&& and ($x && $y) The condition is true only if both inputs are true, otherwise it is false.
and and ($x and $y) The condition is true only if both inputs are true, otherwise it is false.
|| or ($x || $y) The condition is true as long as one of the inputs is true; if both inputs are false, then it is false.
or or ($x or $y) The condition is true as long as one of the inputs is true; if both inputs are false, then it is false.
! not (!$x) Flips or toggles the value of the input from true to false or false to true.
xor exclusive or ($x xor $y) The condition is true only if one input is true and one input is false. If both inputs are true, or if both inputs are false, then the condition is false (e.g., (1 xor 0) is true, while (1 xor 1) is false).

Javascript for Loops

When writing code, it is often desirable to repeat the same chunk of code many times in a row, with minor differences between each iteration. This repetition is what loops are for.

The simplest loop is the for loop. The for loop is a loop that repeates the code written within the loop a fixed amount of times, determined when the loop first begins to execute.

Consider the following example, where the for loop starts at 0 and iterates as long as the index or counter variable (in this case i) is less than 10; in this case, each iteration of the loop increments the index variable by 1 at each iteration.

The way to read this code, is that you are creating a for loop, where the variable i is (declared and) initialized to 0, which will execute as long as i is less than 10, and which will increment by 1 in each iteration. The "i++" is a shorthand for "i = i + 1". Similarly, "i--" is a shorthand for "i = i - 1". Check out the following table for common shorthands:

Table of shorthand assignment notation
Shorthand Longhand
x++ x = x + 1
x-- x = x - 1
x += y x = x + y
x -= y x = x - y

Here's another example of a for loop:

Javascript while Loops

The limitation of the for loop is that you have to know ahead of time how many iterations your loop will need to take. There are many cases where the number of iterations you want your loop to take will be unpredictably variable. In such cases, it is often best to use while loops instead. Anything that is written as a for loop can also be written as a while loop, but not all while loops can be written as for loops. Thus while loops are the more general form.

	while (condition) {
	// do something
	}
	

The way to read this, is that, on each iteration, including the first one, the while loop first checks to see if the condition is true. If the condition is true, then it executes the code in the loop. After executing the code, the while loop goes back to the beginning, checks the condition again, and repeats the process until the condition becomes false.

Here's an example of a while loop; notice, it could not be written as a for loop:

You must be careful using while loops, because it is very easy to inadvertantly create an infinite loop. An infinite loop is a loop that never ends because it's condition is never met. The above example can be made into an infinite loop simply by including a name which is not in the array. The code for the infinite loop would appear as follows (note, I did not script this text, it appears in a <pre> tag):

var i = 0;
var x = students[i];

while (x != "Bob") {
	printVar(x);
	i++;
	x = students[i];
	}
	

The more robust way to fix this code is to put in a check to make sure that you have not exceeded the length of the array which you are looping through:

PHP Loops

PHP also has for and while loops. Their form is similar to javascript:

<?php

for ($i = 1; $i <= 10; $i++) 
{
    echo $i;
}

$x = 1;
while ($x <= 10) 
{
	echo $x;
	$x++;
}

?>
	

Javascript DOM Manipulation

Remember the thing called the DOM (Document Object Model)? This was the tree-like representation of the HTML document where each element was represented by a 'node' in the tree, having attributes associated with it, children nodes beneath it, parents and siblings. Each node in the DOM supports some functions for manipulating the DOM structure - doing things like creating and appending nodes, moving nodes, removing nodes, etc. Read more about DOM.

Here are some useful ones:

  • createElement
  • createTextNode
  • createAttribute
  • getElementsByTagName
  • getElementById
  • appendChild
  • insertBefore
  • removeChild

There are also some JavaScript events you can set on most HTML Elements.

  • onAbort
  • onBlur
  • onChange
  • onClick
  • onDblClick
  • onDragDrop
  • onError
  • onFocus
  • onKeyDown
  • onKeyPress
  • onKeyUp
  • onload
  • onMouseDown
  • onMouseOut
  • onMouseOver
  • onMouseUp
  • onMove
  • onReset
  • onResize
  • onSelect
  • onSubmit
  • onUnload

Loops in action (Javascript)

Name Email

Email address lookup (Javascript)

Here's an example that uses a conditional and a loop.

Please be aware that this example is for instructional purposes only. The code written here is not very robust, and will fail on relatively simple problems, such as adding an extra space at the beginning or end of a name, not capitalizing the name properly, etc. If you were writing a script to do this for real, you'd have to be careful to create more robust code that could handle common errors like those.

Exercise

Below is a short list of exercises. Please select one or more that seem interesting to you and complete them for next class. You may use either javascript, php, or both. You may do this as part of your personal website assignment (recommended), or as a stand-alone exercise. I expect you will run into trouble with these exercises, so be sure to ask for help if you need any. These exercises are due a week from today. However, remember that I will be out of town next week, and may not have reliable access to email, so start early, so that you can ask me questions while I am still around. There will be no lab on Wednesday.

  1. Creat a page where, by clicking on various buttons, you add or remove content in the page via DOM manipulation.
  2. Create a page where, by clicking on various buttons, you change the styling of the page. Note, you might find "style" and "className" to be two useful properties (by having different styles under different class names in your CSS, you can change styles by changing the class associated with a particular element, rather than editing the style with your javascript). See the somewhat related benchmark page on Quirksmode.
  3. Create a page where styles, images, content (or all three) change periodically. One example would be something like a homepage where the news section constantly cycles through all the recent stories.
  4. Create a text box which visitors to your page can type into, and when they click on a button, have the text appear in the page. If you want to get fancy, create some way of letting them choose where on the page the content will appear (this will likely either be a multiple-choice radial button form, or multiple buttons they could click on).
  5. Create a guest-book for your personal website where people can leave their name and email address, and when they hit submit, their information both appears on the page, and gets saved on the server. (You will need to look up how to write to files with PHP to complete this exercise.)
  6. Create a form of some sort, and use javascript to check whether the user has entered in the correct information using javascript (or php, but javascript is more elegant and user-friendly for this task).
  7. Develop your own idea of what you want to try to accomplish with javascript and/or php, and try it out.

Submission

To turn in your assignment, please upload the files you created to your I: Drive. Please email me a link to each file you create, including css, php, and js files.

Grading Criteria

Out of 50 points total.

  • HTML validation for all appropriate files (link + successful validation): 5 points
  • CSS validation for all appropriate files (link + successful validation): 5 points
  • What you did: 40 points