Psy 422 Week 4 - JavaScript

This week we will begin to use JavaScript to do some client-side scripting, and in the process learn some basic concepts of structured programming techniques. Client-side scripts are executed on the user's local machine. Later we will learn to use Perl (and perhaps PHP) for server-side scripting.

JavaScript programs are written in the <head> section of an XHTML document. We will begin with some basics, using JavaScript to write XHTML markup and text to the <body> element of the document. Then we will learn some principles of structured programming, including the use of control structures such as the "if/else" decision structure and the "while" repetition structure. Finally, we will introduce the the concept of object-oriented programming, and learn to use the document object model to interact with form data in JavaScript.


Getting Started with JavaScript

Take a look at these XHTML pages that use JavaScript, and then answer the following questions. Be sure to look at the source of the pages to see how the scripts work. Note that the scripts are enclosed within XHTML comments (between <!-- and -->). Also note that JavaScript comments begin with // and go to the end of a line. Each JavaScript command should be terminated with a semicolon;

1. What is the difference between "write" and "writeln"?

2. Where in the <body> element does the output of the "document.writeln" command appear?

3. How did I get "document.writeln" to put the quotation marks around "nothing"? Why do the quotation marks need special treatment in this context?

4. The "flow of control" refers to the order in which parts of a program are executed. Describe the order in which things appeared in the browser page when you loaded "javascript2.html". What can you conclude about the flow of control in the script and the order in which the parts of the XHTML page were rendered?


Control Structures

The default order in which actions in a program are executed is sequential - statements are executed in the order they appear in the program. Another way of saying this is that after a statement is executed, control is passed to the next statement sequentially. To get a program to do anything really interesting, however, you need to be able to pass control to earlier statements in the program (repetition) or skip statements under certain conditions (selection).

Selection Structures

Selection structures allow the script to take different actions depending on whether some condition is met. The three selection structures available in JavaScript are:

Look at these example web pages and their source, then answer the following questions.

javascript3.html (if and if/else)

The if construction consists of a test condition and an action. If the test condition evaluates as true, the action will be executed. If not, control passes to the next statement after the if block. The action is either a single statement or a block of code enclosed in curly braces {}. Note that individual statements are terminated with semicolons, but no semicolon follows a curly brace.

5. The first instance of "window.prompt" has one argument (line 28) and the second (lines 41-42) has two arguments. What does the first argument do? What does the second do? What happens if only one argument is given?

6. Why does the first window prompt have "undefined" as the initial value of the input string? Does the variable "answer1" have any value defined for it prior to its appearance in line 28? What does that tell you about how the initial value of the input string in a window.prompt box is determined?

7. The if statement in line 34 has a compound condition that uses the or operator. (See pages 296-301 of your text for more information on JavaScript logical operators.) Try giving yes as a response in the prompt window, then reload the page and try Yes, then try YES. What happens?

8. Edit the page, changing || to && on line 34. Then try yes and Yes as responses again. What happens? Why would using && in this way be considered a logic error in a program?

All window.prompt input gets stored as a string. To use the input as a number, you must first convert the string to a number using one of the global functions from p. 341 of your text. Line 44 uses the parseInt function to convert the user's input to an integer, and assign the resulting value to a new variable "answer2Value". (Note: Do not confuse the assignment operator = and the equality operator ==. See p. 301 for a list of JavaScript operators.)

9. Look at the output of the document.writeln statement on lines 45-46, What is the value returned by parseInt if the user input was not a valid number? What happens in the if statement on line 49 when answer2Value is not a valid integer? Try different operators (<, >, <=, >=, !=) and see what the results are to help you figure out the answer.

javascript4.html (nesting)

10. You can nest one if/else structure inside another one, as shown in javascript4.html. Change the values of firstNumber and secondNumber in lines 25 and 26 and rerun the script until you find values that get each of the three statements (Statement 1, 2, 3) to print. List the pairs of values you tried, and which statement printed for each of them.

11. The if statement on line 49 of javascript3.html does not check for invalid input. As you discovered in Question 9, odd things happen when you expect a variable to be a valid number and it is not. Edit javascript3.html so that it first checks to see whether the input can be interpreted as an integer, and only does the comparison in line 49 when it has an integer to work with. If the input can not be interpreted as an integer, print out an error message in the body of the web page instead. Use a nested if or if/else structure to accomplish this.

javascript5.html (switch)

The switch structure selects one action block to execute from among several possible cases, depending on the value of a test expression or variable. It can also include a default action block that will be executed if none of the cases are matched.

12. Notice that the document.writeln statement in line 57 is commented out so that it is not executed. The line above it demonstrates the escape function. Uncomment line 57 and comment out line 56 to see what the unescape function does. Think back (or look back if necessary) to the way data from XHTML forms was emailed to you using the "mailto" option. How does this relate to the escape and unescape functions?

13. Now focus on the switch structure in javascript5.html. What happens if the same value is used in two different case statements? Try changing the value for one of the case statements in javascript5.html and see. What do you conclude about how the flow of control is passed through the switch structure?

14. Now comment out all of the "break" statements in the switch structure and repeat your experiments from Question 13. What happens? What do you conclude about the flow of control in the switch structure, and the function of the "break" statement?

15. Could you use only if structures to do what this switch structure does (as it was originally written before you modified it)? Why or why not?

Repitition Structures

Repitition structures loop through a set of statements for a set number of iterations or until a test condition causes the loop to stop. The four repitition structures available in JavaScript are:

All you really need is while, which tests a condition, then repeatedly executes a block of code as long as the condition evaluates as true. (The test condition is only evaluated at the beginning of each loop, right before the block of code is executed. If the condition is "true" at that point, the whole block of code will be executed before checking the test condition again).

The do/while structure is exactly like while, except that the block of code gets executed at least once no matter what the value of the test condition is.

The for structure iterates over a fixed number of repititions, defined by an index variable that gets incremented after each pass through the loop until a test condition is met and you exit from the loop.

The for/in structure does basically the same thing as for, but it iterates over a fixed set of possible values for the index variable. (Technically, it iterates over all the properties of an object - but more about those terms later.) For/in loops are handy for working with arrays.

javascript6.html (repitition structures)

The file javascript6.html prints the numbers 1-10 in reverse order. This loop is implemented in each of the four JavaScript repitition structures.

16. Which structure seems the most natural one to use for this task? Why?

javascript7.html (while loops to check for valid user input)

The file javascript7.html demonstrates the use of a while loop to validate user input, and also demonstrates some alternative ways of incrementing and decrementing index variables in three of the loops from javascript6.html.

17. Enter the number 10 and observe the output of the script. Then reload and enter the number 3 and observe the output. Which of the three loops has a logic error in it? Make a copy of the file and fix this logic error. Do so before going on to the next question.

18. Try entering different values and strings in the window prompt to see whether it successfully keeps you from entering invalid data. Did you find anything to enter that would "crash" the program somehow? If so, what was it and why did the error checking in the while loop fail to catch it? Fix the script so that no invalid data gets through.

19. Edit javascript5.html so that the script tests for invalid input from the user and makes the user keep re-entering their responses until both the subject number and condition are valid responses. Think about whether you would rather validate and re-prompt for subject number and condition one at a time, or only after both have been entered.

Arrays

An array is an object that holds a collection of numbers, strings, or other data items. Each element of an array has a subscript that can be used to refer to it. Confusingly, the subscripts start at zero for the first element (rather than one). An array is generally created using the new operator, although there are other ways to create arrays also. Arrays in JavaScript are dynamic, meaning that you can add more elements to them after you have created them, allowing them to grow as needed. Take a look at the following file for some examples of using arrays:

javascript8.html (arrays)

Edit the file and answer the following questions. Look for the phrase HOMEWORK QUESTIONS in the comments in javascript8.html to find where you should make your changes.

20. Add an array element to array3 as instructed in the comments in the document source. There are two elements you are told to add; refresh the page in the browser after adding each one. Describe what happens to the table.

21. After adding the two array elements as instructed, change the for/in loop to a for loop and look at the table again. What value do array elements have when you have not yet initialized them?

javascript9.html (sorting arrays)

The file javascript9.html demonstrates a method for sorting arrays numerically. It also demonstrates the difference between passing by reference and passing by value. Arrays in JavaScript are passed by reference, but array elements are passed by value. Look at the source of the script and the output in the web page.

22. What unexpected result occurred in the script due to arrays being passed by reference? How did it happen?

javascript10.html (randomizing)

The following statement will assign a random number between 0 and 1 to the variable randnum:

The file javascript10.html uses the Math.random function to randomize the order of the elements of an array. Every time you reload the file in your browser, you should get a different random ordering of the array. You can use this file to help you create the following web pages:

23. Randomly choose two words from a list of 10 and display them in the browser window. A new random selection should be made each time the page is reloaded.

24. Prompt the user asking how many random numbers they want, then display the integers from 1 to that number in random order.

Valid XHTML 1.0!