CSCI 102T
The Socio-Techno Web
Home |
Schedule |
Labs |
CS@Williams
Lab 8: More Fun with JavaScript!
For this week's lab assignment, you will learn more about using JavaScript
to add intelligence and advanced functionality to your web pages.
Specifically, you will learn about using global variables, if statements, arrays, and
for-loops. These are the basic building blocks that coders use
to write sophisticated programs. After this lab, you should think of
yourself as a capable programmer!
Warmup 1: Global vs. Local Variables
In Labs 5 and 6, you probably used variables to store the values of the user's input
text in your madlib games. For example, many of you had lines of code such as:
var noun1 = document.forms["myForm"]["noun"].value;
After reading in values for all of your variables, you then wrote/displayed your
final madlib/story using those variables. In your JavaScript code,
you probably only defined one function. In general, JavaScript allows you to
define multiple functions. You could imagine, for example, a second function
in your madlib game that actually validated the text being entered. It might have
checked to see if you truly entered a noun when a noun was requested, for instance.
In JavaScript, a variable that is defined within a function is called
a
local variable. Local variables are
accessible to all code contained within a function, but not beyond. If you want to
access a variable in multiple functions, you must declare it outside of a function.
These variables are called
global variables. Generally, we refer to the
accessibility of variables as their
scope within a program. You can read
more about variables and their scope
here
and
here.
Look at the following code:
var counter=0;
function simpleTest() {
counter = counter+1;
alert(counter);
}
Note the use of the global variable counter. Suppose the function simpleTest was
called each time a button was clicked. What would this program do? Check
it out
here. (Recall that you can view the source of this
page in Chrome by Ctrl+clicking and choosing "View Page Source.")
Now imagine that we change the code slightly to use a local variable instead:
function simpleTest() {
var counter=0;
counter = counter+1;
alert(counter);
}
As before, suppose the function simpleTest was called each time a button was clicked. What would
this program do? Check it out
here. Do you understand
the difference? In general, you will find that you often need a combination
of local and global variables in your programs.
Warmup 2: If/Else Statements
In order to add more advanced functionality to our webpages, we must be able to react
in different ways to the user's input, time of day, etc. In other words, you might
want to execute different branches of code depending on a specific condition. In
JavaScript (and most other programming languages), this is accomplished through the
use of an if/else statement. This simple programming construct allows us to perform
one action if a given condition is satisfied, and another action if it is not.
Here is what an if/else statement looks like in JavaScript:
if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is true
} else {
block of code to be executed if the condition1 is false and condition2 is false
}
Note that you don't need to have 3 branches of execution; it's completely ok to just have
an single if statement without an else. The form shown above is the general form of
an if/else statement.
Take a moment to
carefully read more about if/else statements
here.
Try a few of the examples and make sure you understand what's going on. I especially like
the
light bulb
example. If this example does not make sense, ask for an explanation before moving on.
Warmup 3: Arrays and For-loops
Once again, recall your use of variables in Labs 5 and 6.
What if you need to keep track of more than just 5-10 variables? Certainly you could name
each of them individually, but this can be tedious and annoying. In JavaScript (and
most other programming languages), programmers can use a programming construct called
an
array to store multiple values in a
single variable. For example, suppose
I wanted to keep track of the days of the week, but didn't want to create 7 separate variables.
Using an array, this looks like this:
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
To access one of the days of the week, I can just ask for the word at a specific
index.
In the days array shown above, the word at index 0 is Monday, the word at index 1 is Tuesday,
the word at index 2 is Wednesday, and so on.
Note: In JavaScript, indices in an array start at 0! In other words, if I want
the first word or
element in an array, I ask for the 0th element, not the 1st.
For example, the following code would print Tuesday, not Monday.
document.write(days[1]);
Notice the syntax that is used to access the elements in an array. We use the array
name, followed by the index in square brackets
without any spaces.
In many cases, it is useful to be able to
loop through an array, which basically
means we cycle through the array looking at one element at a time. The best way to do
this is using something called a
for-loop. For-loops allow us to quickly and
easily iterate over all elements in an array. For example, look at the following code:
var index;
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
for (index=0; index < days.length; index=index+1) {
alert("index = "+index+" and the day is "+days[index]);
}
This code loops through our days of the week array, and simply pops up an alert with
the index value and day for each of our 7 days. Let's look at the structure of the
for-loop a little closer. The for-loop has the following basic syntax:
for (statement 1; statement 2; statement 3) {
code block to be executed
}
Here, the code located at "statement 1" is executed
before the loop (the "code
block") starts. In this case, we are just setting index=0. Statement 2 defines the
condition for running the loop. In other words, statement 2 specifies a property that
must be true in order for the loop to keep running. In our days of the week example, the loop should keep
running as long as index < days.length. (Note that days.length is a built-in function
that tells you how many elements exist in the days array. days.length is 7 in our case.) Statement 3 is executed
once at the end of the loop, i.e., after the code block has been executed. In the above
example, we are simply adding 1 to index. The end result is that our loop will execute 7 times,
printing out the value of index and each day of the week exactly once before exiting.
You can try it yourself
here. You can also experiment on your own by Ctrl+clicking
array.html, saving this to your www directory,
and checking out the code.
Before continuing, carefully read through
this page on JavaScript arrays,
and
this page on JavaScript for-loops.
Exercise 1: Binary Search
Recall the classic "Pick a Number" game that involves one person randomly picking
a number in some range (say 1 to 100), and then a second person trying to guess that
number. The first person often gives the guesser clues such as "higher" and "lower" to
help the guesser find the right number quickly.
The optimal strategy for the guesser
involves a classic Computer Science algorithm called a
binary search. You can read more about
binary search
here.
Basically, the guesser first guesses the midpoint of the
range of numbers, i.e., 50 in a game from 1 to 100. Then, based on the first person's
response, the guesser either guesses 25 (the midpoint between 1 and 50) or 75 (the midpoint between
50 and 100) depending on if they were too high or too low the first time. By repeatedly
choosing the midpoint of the remaining acceptable range, the guesser eliminates half of
the remaining viable guesses on each turn, which is where the name
binary search
originates. This strategy will allow the guesser to consistently find the answer in
the fewest number of turns.
Your task is to build this simple game. You can assume that the range of numbers is
between 1 and 100. You can also make use of the following JavaScript code that will
randomly pick a number between 1 and 100:
var target = Math.floor((Math.random() * 100) + 1);
- Start by Ctrl+clicking and saving binary-search.html
to your www directory. I have left comments in both the JavaScript code and
HTML code to help guide your efforts.
- Scroll down to the body of the page. Create the HTML form and button just as you
did last week. This week there will only be one textbox for entering the guessed value.
- Fill in the JavaScript code in the header. You will need to define a global variable
for holding the target value. Assign the target a random value between 1 and 100.
- Finally, you need to create an if/else statement within submitGuess() for checking to see
if the target value was entered. IMPORTANT: To check for equality between two numbers
in JavaScript, even when using variables, you use two equal signs within the if statement's
condition. You can find more info here.
For example, look at the following sample code that checks to see if x is
equal to 5:
if (x == 5) {
alert("x is 5.");
}
You also need to check to see if the value entered was higher (>) or lower (<) than the target,
and make a suggestion (using alerts) about guessing higher or lower on the next round.
You do not need to worry about having the game automatically repeat.
Exercise 2: Hangman!
For our final exercise, we'll revisit another classic game: Hangman. Put simply,
Hangman is a game where the player has to guess the letters in a secret word before
being hanged. Each time an incorrect letter is guessed, a new body part is added
to the hanging person. (In retrospect, this game is rather dark...)
- Start by Ctrl+clicking and saving hangman.html
and hang.zip
to your www directory. Double click on hang.zip to expand the zip file.
The basic HTML for your game has already been provided for you. You should look
over it, however, since you will have to manipulate various parts of it in the
code that you write. I have left comments in the JavaScript code
to help guide your efforts.
- The bulk of your work involves filling in the JavaScript in the body of the
page. You should be able to follow the comments (i.e., the lines that start with //)
to help you. Remember that the purpose of this lab is to gain experience with
variables, arrays, if/else statements, and for-loops. Most of the other
code is provided for you. However, you should understand all of it at this point!
- The dictionary consists of 5 letter words.
Feel free to add others!
- Extra credit opportunity: extend the code to work for words with varying
size (rather than all words having 5 letters).
Tasks for lab
- Spend a few minutes making sure your webpages are up to date. Fix broken links,
rerun the HTML and CSS validators to make sure everything still works.
- Carefully read and understand all 3 Warmup sections.
- Complete Exercises 1 and 2. In the end, you should have completed versions of
binary-search.html and hangman.html.
- Save your files and test often! Have fun!
HTML Validator