LIS 390W1A - Javascript Exercise #3: Loops & Conditionals

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.

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 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)
!= 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:

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:

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:

Of course, this gets to be a pain to type out, which is why the switch statement was developed.

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.

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 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:

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:

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:

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

Name Email

Email address lookup

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.