Lab 4.1

advertisement
Lab 4.1
Getting Started With JavaScript
Read: Chapter 18
In previous labs, we worked with HTML and saw how to use that language to describe how a web page
would look. A web browser would read an HTML file (typically via the network) and visually display
the page according to the HTML. In this lab, we’ll see how we can use the JavaScript programming
language to enhance web pages. We can add JavaScript instructions to an HTML file, and the web
browser, in addition to displaying the page as described in HTML, can execute those instructions. You
can think of this like putting small programs inside web pages, which enables them to much more than is
possible with HTML alone.
Discussion and Procedure
Part 1. Introduction to JavaScript
Before we dive into working with JavaScript, we’ll introduce you to the language and answer a few
common questions about it. This background information should help you make sense of the steps
required to write and run JavaScript programs.
What is JavaScript? JavaScript is a programming language, and like any programming language, it’s
used by humans to communicate instructions to computers. JavaScript’s most common application is
for enhancing web pages. In fact, although JavaScript is in fact used in contexts other than web pages,
in these labs, we’ll only work with JavaScript with web pages. More specifically, we will never see a
JavaScript program by itself; instead, every JavaScript program we write will be written as part of a web
page, and we’ll use a web browser to run the programs. In this sense, you can think of JavaScript as an
extension to HTML. As you’ll see in this lab, you literally write JavaScript programs inside your
HTML web page files.
Is JavaScript the same as Java? “No,” is the short answer. Although the names of the languages are
misleadingly similar, JavaScript and Java are in fact very different languages with only superficial
similarities. Unlike JavaScript, which (as mentioned above) is generally used to enhance web pages,
Java is a general-purpose programming language and can be used for much more than just web
programming. If you are interested in learning more complicated, more general-purpose programming
languages like Java and C++, however, you’ll be encouraged to know that JavaScript was deliberately
designed to at least superficially resemble these languages, if only in terms of syntax. (Loosely
speaking, the syntax of a programming language is like the spelling rules, grammar, and vocabulary of
the language.)
How do I run a JavaScript program? When a JavaScript program is written in a web page, all you need
to do is open the page in a web browser to run the program. All recent versions of popular web
browsers (e.g., Mozilla, Netscape, Opera, Internet Explorer) are capable of running JavaScript programs
in web pages.
1
Lab 4.1: Getting Started with JavaScript
What happened to compilation? Chapter 9 discussed what’s happening behind the scenes (or rather,
“inside the box”) when a computer runs a program. With programming languages like C, C++, and
Java, code is compiled and translated into machine instructions that the computer can more readily
understand and saved in a program file that can then be run by itself. There is special software called
the compiler which does this translation and saving. In the case of JavaScript, there is no compiler.
Instead, web browsers include special software called an interpreter, whose job it is to translate the
JavaScript code into machine instructions “on the fly,” each time the program is run. From the
programmer’s point of view, this is easier, because they don’t need to run the compiler whenever they
want to try running their program. On the other hand, since the code has to be translated into machine
instructions as the program runs, programs written in languages like JavaScript are often slower than
those written in compiled languages.
Where have I seen JavaScript already, perhaps without recognizing it? Many popular web sites use
JavaScript in subtle ways in an effort to make their pages more interesting and easier to use. You can
use JavaScript to set up your web page so that special effects happen when you click or move the mouse
over certain parts of the page. If you’ve ever filled out a form on a web page or seen images change
when you hover your mouse over them, you were probably seeing JavaScript in action.
How do I write a JavaScript program? From reading Chapter 18, you’ve already seen what JavaScript
code looks like, but you might be wondering where you should be putting this code to run it. As we’ll
see later in this lab, all you need to do is put your JavaScript code in a special section of an HTML file
(marked off by tags), and opening that web page in a browser will run the code.
Do I need my own web space or a web server to write and run my own JavaScript? You might be
surprised to know that you do not need space on a web server to work with JavaScript. In the same way
that you can write an HTML file and open it on a computer that’s completely disconnected from the
Internet, you can write and run JavaScript programs on a non-networked computer. However, if you
want other people to be able to view your JavaScript-enhanced web pages, then you do, of course, need
to upload those web pages to a web server somewhere.
Part 2. Downloading and running a JavaScript program
The first thing you need to do to start experimenting with JavaScript is to set up our tools: the software
we’ll use to write and execute the programs. The two main tools we need are a text editor and a web
browser. In this lab, we’ll assume you’re using two commonly available tools on the Windows
platform: Notepad and Internet Explorer (IE). However, almost all of these instructions are general
enough that you should be able to complete this lab with any text editor and modern web browser.
1. On the CSIS 1 Web page, next to the Lab4.1 link, click on the link called Lab4.1_JS_Demo.
This is just an example web page with a very simple JavaScript program (just one line long, in
fact!) inside it. The program just pops up a dialog box with a simple message when the web
page is loaded in a browser.
2. In the browser window, click on Refresh to run the program again. Then click View>Source and
examine the contents of the file, noticing where the script tags have set off a portion of the
webpage where the JavaScript language is inserted. You can change the program, however, in
2
Lab 4.1: Getting Started with JavaScript
order to be able to modify and rerun the file, you will first have to download it to your local
computer. To do this, close Notepad and follow step 3.
3. Download the page to your local computer so you can modify it. Go back to the CSIS 1 page (In
the browser, click on the back-arrow). Then Right-Click on the same link you just visited, choose
Save Target As, then navigate to the desired location—on campus use U: (Network Drive) or at
home use My Documents, then click Save.
4. Open the folder where you saved the file on your computer using MyComputer or Windows
Explorer, then double-click on the file Lab4.1_JS_Demo.htm to run it from your local computer.
The page should work the exactly the same as if you loaded it in from the internet. Return to
MyComputer or Windows Explorer, right click the file and Open With... Notepad.
5. Make sure to leave the Notepad window open when you go on to the next part. We’ll be editing
this JavaScript program, so it’s convenient to leave it open.
Part 3. “Breaking” the program and other experiments
If all went well in the previous part of the lab, you successfully ran a JavaScript program. It’s valuable
to know how things work when you have a correct program, but it’s equally (if not more) valuable to
know how your browser will react when you open a web page with an incorrect JavaScript program.
After all, even the best of us will frequently have to deal with mistakes (“bugs”) we made writing our
programs. For this reason, in this part of the lab, we will concentrate on experimenting with our little
HTML file, changing the JavaScript (sometimes intentionally putting bugs in it) and seeing what
happens when we run it. (You might remember that we did the same kind of experimenting with HTML
in an earlier lab.)
3
Lab 4.1: Getting Started with JavaScript
We’ll start simple and make some legal changes to the JavaScript program (i.e., we won’t add any bugs
yet). This will help us get used to switching between editing and running the JavaScript. At this point,
you should still have a Notepad window with the HTML source and a web browser window with the
page open.
6. Change the alert message. In the Notepad window, change the alert message string to another
short phrase of your choice. Make sure the quotation marks are still around the phrase and
remember to save your change when you’re done.
7. Reload your browser window. And verify that you new message shows up. If not, get help from
the instructor.
All you need to do to update and rerun your program is save in the Notepad window and reload in the
browser window.
8. Add a second alert to the program and reload the page. Back in the Notepad window, copy
the alert line and paste a copy right after the original alert line. Give it a second (different)
alert message. Make sure there’s a semicolon at the end of each line and save your changes
before running the program.
Describe what happens when you reload the web page.
9. Change the first alert line to the line shown below. This is the first bug we’ll intentionally
introduce.
alert("hi";
What is the problem with the line above?
10. Reload the page in your browser. Describe what happens.
It’s evident that something isn’t quite working right, because your second alert line ought to be fine.
We already know what’s wrong, but let’s use this as an opportunity to learn about some strategies you
can use to troubleshoot your JavaScript programs. These strategies should prove helpful later on when
you’re working with longer, more complicated programs, where it can be more difficult to identify what
line(s) of your program are going wrong.
All of the popular web browsers are capable of displaying some information about what went wrong
with a JavaScript program, e.g., what line of your script appears to be causing a problem and what kind
of problem it’s causing. We’ll show you how to set up your web browser to display these error
messages when a buggy JavaScript is executed.
11. With Internet Explorer, from the menu bar, select Tools \ Internet Options... and click on the
Advanced tab. Under Browsing, find Display a notification about every script error and make
sure its box is checked. The next time a JavaScript program causes an error, a dialog box will
appear, and clicking the Show Details button on the dialog box will allow you to read the error
message.
4
Lab 4.1: Getting Started with JavaScript
12. Try reloading the browser again. This time, you should get some error message. What line does
the browser say the error is on?
What is the error, according to the error message?
Indeed, if you hadn’t noticed already, a close-parenthesis is missing at the end of the second line
of code, just before the semicolon.
13. Correct the bug and reload the page. Describe what happens now.
So you want to see line 754 of your HTML file? No, you don’t have to move to the top of
your file and start counting as you hit the down arrow key! Most text editors have some option
to allow you to move to a specific line number in your file. As simplistic as Notepad is, it
supports “jumping” to a specific line by selecting, from the menu bar, Edit \ Go To… or typing
Ctrl-G and entering a line number. (Note: this will only work when Format\Word Wrap is
NOT checked.) Using Ctrl-G is especially handy when a JavaScript error message reports a
specific line number in a large file, and you want to find that line in your file to start debugging.
This is essential if you’re using Internet Explorer, because when it reports a script error, it only
tells you the line number and doesn’t show you the line of code itself, unlike Netscape/Mozilla
and Opera.
Unfortunately, web browsers can only catch certain kinds of errors and report them. Experiment with
each of the following changes and determine whether an error message results.
5
Lab 4.1: Getting Started with JavaScript
14. “Break” the opening <script> tag by removing the < character. Does reloading the page
result in an error message? What is displayed on the web page?
15. Undo the last change and remove the close-parenthesis in the second alert line. What, if any
error message, results when the page is reloaded?
Part 4. The Assignment
The rest of the lab is to complete the exercises below by filling in code inside the file called
Lab4.1_Assignment.htm, which appears as a web links beside the Lab4.1.doc link on the CSIS1 web
page. These exercises will take you through various simple tasks involving displaying information,
creating variables, and even a simple algorithm.
16. Right click on the link Lab4.1_ Assignment.htm which is on the CSIS1 web page. Choose
File>Save Target As and save the file either on your U: drive (on campus) or My Documents
folder (at home).
17. Find the file where you saved it, then double click on it to open it in Internet Explorer. You
should get a page that simply says “Hello World” on it. Go to MyComputer to open the file in
Notepad for editing by right-clicking and choosing Open With ... Notepad.
18. Notice this file has a number of comment lines (beginning with /*--- or //----) which are
ignored by the computer but serve to indicate places where you can enter your answers for the
exercises that follow. The comment lines can activate or deactivate different parts of your
program as you work on the various exercises. The first exercise will be entered right beneath the
line beginning /*---------- Exercise 1------------ in the file.
19. To activate each Exercise, simply put one more / in front of /*-----in other words,
//*------------When you’re finished with an exercise, remove the extra / to deactivate it.
Section 1: Displaying Values and Expressions
Write Statements
The simplest form of output in JavaScript is produced via a document.write statement (or simply
write statement for short). Using document.write, any message can be displayed on the screen. For
example, the following statement, when typed into the JavaScript interpreter, displays the message
Hello world! on the screen.
document.write("Hello world!");
In general, any message can be displayed by such a write statement, simply by inserting the desired text
in between the quotes. Note that the quotes do not appear in the output.
Exercise 1: If you have not already done so, configure your browser and Notepad as described in Step
16 and 17. In Notepad, you’ll find under /*------- Exercise 1----- the hello world statement listed above.
6
Lab 4.1: Getting Started with JavaScript
Activate this line under exercise 1 by adding a / before /*-----Exercise 1 ( //*-----Exercise 1), then
save the file in notepad and reload the file in your browser. You should see the message
Hello World!
For this exercise, simply modify the message in the write statement so that instead of greeting the world,
it greets you in particular. That is, if your name happens to be Dave, alter the statement to output Hello
Dave!
Augmenting Output Messages
The messages that you write to the document can be formatted just like in HTML. In fact, if you want to
display, for example, a haiku, using document.write,
The first cold shower;
Even the monkey seems to want
A little coat of straw.
You’ll have to add <br> symbols to the text of the write statement. For example, the following write
statement will actually produce three lines of output.
document.write("Line 1 <br> Line 2 <br> Line 3 ");
Exercise 2: Activate the exercise 2 by adding a / before /*-----Exercise 2 Save and run the
program by reloading the web page. Notice the haiku formatting is all on one line. Now, edit the
messages in each write statement to contain the <br> tag at the end (inside the quotes).
document.write("The first cold shower<br>");
Note that the <br> tag is inside the message, i.e., inside the quotes. The haiku should now appear on
three separate lines.
Data Types and Expressions
So far, you have used the JavaScript write statement to display messages (you could have done this in
HTML without JavaScript). Such messages, text enclosed in quotes, are known as strings. In addition to
strings, data values in JavaScript can also be numbers and booleans (true/false values that will be
explored in a later Lesson). Each of the data types in JavaScript has operators predefined for
manipulating values of that type. Not surprisingly, the standard arithmetic operators '+' (addition), '-'
(subtraction), '*' (multiplication), and '/' (division), are predefined for numbers. Strings also have
numerous operators predefined for them, including string concatenation.
In addition to strings, any type of value can be displayed using a write statement. For example, the
following write statement will output the product of 3 and 7, i.e., 21.
document.write(3 * 7);
7
Lab 4.1: Getting Started with JavaScript
Strings and numbers can even be mixed together in a write statement, such as
document.write("The product of 3 and 7 is " + (3 * 7) + " <BR>");
Exercise 3: Sometimes, the order in which an expression is evaluated is important to the final result.
Consider the following expression, for example:
2 + 4 * 5
If the addition is performed first, the expression will evaluate to 30. If the multiplication is done first,
however, the expression will evaluate to 22.
2 + 4 * 5
2 + 4 * 5
==>
==>
(2 + 4) * 5
2 + (4 * 5)
==>
==>
30
22
In any programming language, precedence rules define the order of evaluation for such expressions. In
JavaScript as in mathematics, multiplication has precedence over addition, so the multiplication will be
performed first (resulting in 22).
Addition and subtraction have the same precedence, as do multiplication and division. If more than one
operator of the same precedence appears in an expression, they are evaluated from left-to-right. Thus,
8 / 4 / 2
==> (8 / 4) / 2 ==> 1
Of course, you can always force a particular order of evaluation by using parentheses. In fact, it is
inadvisable to rely too heavily on the precedence rules and left-to-right nature of evaluation. If you write
a complex expression, parenthesize it to make sure that the desired order is used.
For this exercise, try to predict the value of each of the following expressions, entering them where
indicated under Exercise 3, then test your predictions by placing the expression inside a document.write
statement, ( do not use “”). For example, the test for a) is already included under this exercise with the
statement
document.write(3 + 3*2 + 1);
To test the others, simply replace the expression 3 + 3*2 + 1 with the expression you would like to test.
a)
3 + 3 * 2 + 1
b)
10 / 2 * 5
c)
7 - 2 - 4
d)
7 - (2 - 4)
e)
3 * (5 / 2) + 2 * 8
String Concatenation
The only operation on strings that we will consider for now is concatenation, i.e., joining two strings
together end-to-end. String concatenation is accomplished using the '+' operator. For example, the
concatenation of
8
Lab 4.1: Getting Started with JavaScript
"foo" + "bar"
yields the single string "foobar". Just as with addition on numbers, concatenations can be chained
together, so that
"foo" + "bar" + "biz" + "baz"
yields "foobarbizbaz".
String concatenation can be useful in displaying long messages. Since a long string can be broken into
pieces and then put back together using concatenation, it is possible to split parts of a message across
several lines in the same write statement. For example, the following quote by Carl Farrell could be
displayed using three different write statement, or a single write statement split across three lines.
document.write("The easiest way to tell the difference ");
document.write("between hardware and software is to kick ");
document.write("it. If it hurts your toe, it's hardware.");
document.write("The easiest way to tell the difference " +
"between hardware and software is to kick " +
"it. If it hurts your toe, it's hardware.");
Exercise 4: Using string concatenation to break the quote across several lines, give a single write
statement that displays the Farell quote above. Modify the statements in this exercise to look like the
bottom example above and verify that you still get the same output.
Exercise 5: It may seem a little strange for the '+' operator to perform double duty in JavaScript.
When applied to two numbers, it represents addition. When applied to two strings, it represents
concatenation. The question remains, what happens when you apply it to a number and a string? The
answer is simple: the number value is automatically converted to a string (e.g., the number 123 becomes
the string "123") and then concatenation takes place. Thus, the expression
"We're number " + 1
yields the string "We're number 1".
Recall that expressions are evaluated from left-to-right. Thus,
when an expression involving both numbers and strings is evaluated, order is important. For example,
the expression
3 + 2 + " is the sum"
will evaluate to the string "5 is the sum" since the leftmost terms (numbers 3 and 2 ) are handled first
using addition. Their sum, 5, is then converted to a string in order to be concatenated with " is the
sum".
What do each of the following expressions evaluate to? Describe the steps involved in each
evaluation. Enter your predictions for these expressions, then verify them by running the program for
this step.
a)
"The sum is " + 3 + 2
b)
"The sum is " + (3 + 2)
9
Lab 4.1: Getting Started with JavaScript
Section 1 Summary

The simplest means of displaying values in JavaScript is the document.write statement.

By including the HTML tag <BR> in the message to be written, a line break will be appear in the
output.

Numerous other HTML tags can be included in output values in order to format them, such as
<B></B>, <I></I>, <U></U>, <BLINK></BLINK>, and <FONT COLOR='red'></FONT>.

JavaScript has three basic data types: strings, numbers, and booleans.

The basic arithmetic operators '+' (addition), '-' (subtraction), '*' (multiplication), '/' (division), are
provided for numbers.

In JavaScript, multiplication and division have higher precedence than addition and subtraction.
Among operators with the same precedence, expressions are evaluated in a left-to-right order.

Strings can be concatenated (i.e., joined end-to-end) using the '+' operator.

When the + operator is applied to a string and a number, the number is automatically converted
into a string and then the two are concatenated.
Section 2: Variables, Assignments and Conditionals
Continue this lesson by moving on through Lab4.1_Assignment.htm. When defining algorithms, it is
often convenient to give names to specific values since the names make it easier to refer to those values
repeatedly. For example, in the lab on algorithms we considered a method for averaging a list of values.
In defining this algorithm, it was convenient to refer to intermediate results such as the sum of the
values. By giving these values names (e.g., sum), it is easier to describe the algorithm.
Similarly, suppose you wanted to convert a temperature from degrees fahrenheit to degrees celsius. If
we let tempInFahr refer to the fahrenheit temperature, then the corresponding temperature in degrees
celsius is
tempInCelcius = (5/9) * (tempInFahr - 32)
This formula describes an abstract relation between any fahrenheit temperature and its celsius
equivalent. Any temperature can be converted simply by substituting the appropriate value for
tempInFahr in this formula.
10
Lab 4.1: Getting Started with JavaScript
For example:
tempInFahr = 212;
tempInCelcius = (5/9) * (tempInFahr - 32);
is equvalent to:
tempInCelcius = (5/9) * (212 - 32);
which evaluates to:
tempInCelcius = 100;
Variables
In programming terms, a name that refers to an arbitrary value is known as a variable. In JavaScript, a
variable name can be any sequence of letters, digits or underscores that starts with a letter. For
example, all of the following are valid JavaScript variable names:
tempInFahr
SUM
current_age
Sum2Date
Note also that JavaScript is case-sensitive, meaning that capitalization does matter. Consequently, names
such as sum, Sum, and SUM each represent different variables!
Exercise 6: Each of the following is invalid as a JavaScript variable name. Explain why and type your
answers into the file Lab4.1_Assignment.htm under exercise 1 (do not activate or run this exercise, Just
type your answers).
2hotforU
salary$
two words
"sum_to_date"
Memory Cells & Assignments
In the abstract, a variable is a name that represents some value. In practice, this is accomplished by
associating with each variable a piece of memory, known as a memory cell. Each memory cell inside the
computer stores the value of its corresponding variable.
11
Lab 4.1: Getting Started with JavaScript
In JavaScript, values are assigned to variables (and thus stored in their corresponding memory cells)
using the assignment operator '='. For example, the following assignments assign values to the variables
num and name.
num = 10;
name = "Dave";
As a result of the first assignment, the number 10 is stored in the memory cell corresponding internally
to num. Similarly, the string "Dave" is stored in the memory cell corresponding to name. When reading
such statement aloud, read the '=' symbol as gets, as in 'num gets 10' or 'name gets "Dave"'.
Assignments to variables can be visualized by drawing a box to represent the memory cell, labeled by
the variable name:
10
"Dave"
num
name
Once you have assigned a value to a particular variable, you can then use that variable in any expression.
When the expression is evaluated, the variable name will evaluate to its assigned value, i.e., the value
stored in its associated memory cell. For example, the first write statement below will output the number
10, since that is the value of the variable num when the write statement is executed. Similarly, the second
write statement will output "Dave".
num = 10;
document.write(num);
name = "Dave";
document.write(name);
Using these variables in more complex expressions, the following write statements will output 1000 and
"Hello Dave!", respectively.
num = 10;
document.write(num * num * num);
name = "Dave";
document.write("Hello " + name + "!");
These simple examples demonstrate one of the common uses of variables. Using a variable, a complex
expression can be much easier to modify and reexecute. For example, suppose you wanted to compute
the cube of 20 instead of 10. All you would have to do is change the assignment to num, assigning the
variable to have value 20 instead of 10. Since the expression in the write statement relies entirely on the
value of num, it can simply be executed as is. Thus, the use of a variable makes it possible to make only
one change in the assignment as opposed to three changes in the expression itself. Similarly, you could
change the target of the "Hello" greeting to any name just by changing the assignment to name.
12
Lab 4.1: Getting Started with JavaScript
Exercise 7:
Consider the following JavaScript code:
var tempInFahr, tempInCelsius;
tempInFahr = 98.6;
tempInCelsius = (5/9) * (tempInFahr - 32);

document.write(tempInFahr + " fahrenheit = " +
tempInCelsius + " celsius");
By changing the value in the first assignment and then executing the code, convert each of the following
temperatures from degrees fahrenheit to degrees celsius:
a)
98.6 fahrenheit
b)
32 fahrenheit
c)
100 fahrenheit
d)
212 fahrenheit
Exercise 7B: It would be much easier to do Exercise 7 above if you had some way to input the
temperature in fahrenheit rather than changing the value, saving the program, and refreshing your
browser. That way the program could be used over and over again to calculate all the temperature
conversions you wanted. An easy way to get input from the terminal is with the prompt command.
To try this out, change the line reading tempInFahr = 98.6; (second one above, marked with )
To tempInFahr = prompt("Enter temp in F");
This will present a dialogue box to the computer user and ask them to enter a value. Now you can type
any value you want and get the equivalent temp in Celsius. Run the modified exercise 7 a few times to
recheck your answers from above.
Exercise 8: Using the the code from the previous exercise as a model, write your own code to do the
opposite conversion, from degrees celsius to degrees fahrenheit. Think Algebra! Hint: to find the
temperature in Fahrenheit, multiply the temperature in Celsius by 9/5, then add 32 to the result.
For example, for a temp in Celsius of 100, 9/5*100 is 180. Adding 32 gives you 212, which is in
Fahrenheit. Use the prompt command to accept input from the terminal. When you have it working,
execute your code to convert the following temperatures and also type the answers where indicated in
the file:
a)
0 celsius
b)
100 celsius
c)
20 celsius
d)
-10 celsius
13
Lab 4.1: Getting Started with JavaScript
Exercise 9: What do you think would happen if you used a variable in an expression without first
assigning that variable a value? While this is something you might never intend to do, typos happen. For
example, suppose you accidentally misspelled a variable name in an expression:
tempInFahr = 98.6;
tempInCelsius = (5/9) * (tempInFehr - 32);
What would you expect to happen as a result of executing this code? Verify your prediction in the
JavaScript interpreter and report the result.
Order of Execution
In general, the right-hand side of an assignment statement can be any expression. When an assignment
statement is executed, the expression on the right-hand side is evaluated first, and then the resulting
value is assigned to the variable on the left-hand side. For example, consider the following sequence of
assignments:
x = 14;
y = 33 * 10 + 1;
z = x + y;
In the first assignment, the right-hand side is a simple number value, 14, which is assigned to the
variable x. In the second assignment, the right-hand side is a more complex expression which evaluates
to 331, which is then assigned to y. In the last assignment, the right-hand side is an expression involving
the variables x and y. Since x currently has the value 14 and y has the value 331, the sum evaluates to
345, which is then assigned to z.
Exercise 10: Consider the following sequence of assignments. Trace through the code and try to
predict what will be output by each write statement. First, enter your predictions where indicated in the
file. Then verify your predictions in the JavaScript interpreter, and report the results.
a)
var num1, num2;
num1 = 10;
num2 = 2 * num1 + 1;
document.write("num1 = " + num1 + ", num2 = " + num2 + "<br>");
b)
var num3;
num3 = num1;
num1 = 5;
document.write("num1 = " + num1 + ", num3 = " + num3 + "<br>");
c)
var a,b,c;
a = 100;
b = a / 10;
c = (100 - b) / 9;
document.write("a = " + a + ", b = " + b + ", c = " + c + "<br>");
14
Lab 4.1: Getting Started with JavaScript
d)
var word1, word2;
word1 = "foo";
word2 = word1 + word1;
word1 = word2 + a;
document.write("word1 = " + word1 + ", word2 = " + word2 + "<br>");
Exercise 11: In mathematics, where '=' is used for equality, an expression such as the following
wouldn't make much sense.
x = x + 1
In JavaScript, however, you must keep reminding yourself that "=" is used for assigning values to
variables, not for testing equality. As in any assignment, the expression on the right-hand side of an
assignment is evaluated first using the current values of variables. Then, the value of that expression is
assigned to the variable on the left-hand side of the assignment.
Consider the following assignments:
a)
var x = 9;
x = x + 1;
b)
var word = "foo";
word = word + "!";
What values will be stored in the variables x and word after these statements have been executed? After
putting your predictions in the file, add the JavaScript statements in the file to confirm your
predictions.
Exercise 12: We will close this brief introduction to programming with an example of a conditional
(if-else) statement. The following code asks for a name and an age and displays a different greeting
based on the age entered.
var name, age;
name=prompt("Please
age=prompt("How old
if (age < 30)
alert("Hello,
else
alert("Hello,
identify yourself: ");
are you?");
" + name + ", whazzup?");
" + name + ", old chap, how do you do?");
The conditional statement works by performing a test with a relational expression: (age < 30) in this
case. If the value stored in age is smaller than 30, the first message is displayed. Otherwise (if age is
larger or equal to 30) the second message is displayed. Run the program several times to try out the
different values of age and get the two messages to come up.
Although this method works fine for two messages, what if we want more varieties? We can “nest” the
if-else statement by inserting another if-else as the statement to execute in the else category. That is…
15
Lab 4.1: Getting Started with JavaScript
if ( age < 30 )
message for young person…
( where message is in an alert command)
else
if (age < 60)
message for middle aged person…
else
message for older person…
We can adjust the layout a bit to make things simpler to read by moving the lines like the following:
if ( age < 30 )
message for young person…
( where message is in an alert command)
else if (age < 60)
message for middle aged person…
else
message for older person…
We can even check an exact age using the == symbol (Note: NOT =)
if ( age < 30 )
message for young person…
( where message is in an alert command)
else if (age == 42)
alert("Hey that's the same age as me!!");
else if (age < 60)
message for middle aged person…
else
message for older person…
Add a few more messages to the exercise 12 code using the ideas suggested above.
Section 2 Summary

A variable is a name that is used to represent some unspecified value in an expression.

In JavaScript, a variable name can be any sequence of letters, digits, and underscores starting
with a letter. Since JavaScript is case-sensitive, capitalization matters.

Each JavaScript variable has a corresponding memory cell which stores its value. A value is
assigned to a variable (and thus stored in the corresponding memory cell) using the assignment
operator '='.

When evaluating an assignment, the expression on the right-hand side is evaluated first, and the
resulting value is then stored in the memory cell corresponding to the variable on the left-hand
side.

Any attempt to write or use a variable in an expression without first assigning it a value will
result in an error.
16
Download