Reading: JavaScript and jQuery, pages 1-60.
Today we'll learn some basic JavaScript programming through a sequence of simple examples.
JavaScript is a different language from HTML or CSS.
But, as with CSS,
we can include JavaScript code inside an HTML document.
JavaScript code can be embedded
inside both the head and the body
of an HTML document.
Use the <script>
HTML tag to tell the browser
that you are about to write JavaScript code (just as the
<style>
tag introduces CSS code):
<html> <head> ...head elements... <script type="text/JavaScript"> ...JavaScript code... </script> ...more head elements... </head> <body> ...body elements... <script type="text/JavaScript"> ...more JavaScript code... </script> ...more body elements... <script type="text/JavaScript"> ...even more JavaScript code... </script> ...even more body elements... </body> </html>
In the above skeleton, there are three segments of JavaScript code
spread out over the head and body of an HTML document.
In general, there can be any number of JavaScript code segments
delimited by <script>
tags in an HTML document.
JavaScript code can also be put in external files, which facilitates sharing JS code among several HTML pages. This is exactly like external CSS files and for exactly the same reasons. In fact, the modern approach is to keep all or almost all of the JavaScript code separate from the HTMl file. The tag to do so is pretty simple:
<script type="text/JavaScript" src="url/of/file.js"></script>
As you know, we'll be using a JavaScript library called jQuery, so whenever you want to use that library of code (specifically, version 1.8), you will put the following tag in your HTML file:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
Because JavaScript typically adds behavior to an existing
document, we will be putting our script
tags
at end of the file, after all our HTML/CSS and right before
the </body>
tag that closes the body. You will find
books and tutorials and other resources that advocate
putting script
tags in the head (including prior offerings
of CS110), but putting them at the bottom has several advantages:
script
tag,
particularly a tag that loads an external JavaScript file, it has no
choice but to wait for the whole file to load, because that file might
create additional HTML/CSS that needs to be processed before the
browser goes on. By putting the script tags at the bottom, the user
will see the top of the file right away and may not even notice the
several extra seconds required to load the JS.
onLoad
event
handlers in order to have our JS run after the page loads. The page
will already be loaded when our JS runs.
So, for this course, you will put your JS script tags at the end of the HTML page. Your page template will look like this:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title></title> <meta name=author content="your name here"> <link rel="stylesheet" type="text/css" href="path/to/style.css"> </head> <body> <!-- HTML here --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script> <script> /* your JavaScript/jQuery code here */ </script> </body> </html>
Feel free to copy/paste that template when you're starting a new web page.
We're going to use JavaScript to do interesting things, to solve problems, to interact with the user. Over the rest of the course, we'll see lots of ways to do things using JavaScript, but for now, we're going to talk about a conventional way of thinking about computing.
Computing often works like this sequence of steps:
(These terms of gather/compute/report are not standard in the field; we just made them up. If you think of better terminology, let us know.)
We will begin our investigation of JavaScript by presenting a series of simple but working examples. We'll show you the code, but you should not try to completely understand it at this point. Instead, you should read it, make some guesses as to what various things might mean, and try to get the gist of what is happening without worrying about all the details. Later, after we have explained some of the notation and its meaning, we can go back to these examples and understand them more fully.
(This is a little like trying to learn a foreign language by walking around the country, listening to the words people say and observing what they do. You'll miss a lot, especially at first, but it's way more interesting than trying to start by reading a dictionary and memorizing vocabulary and syntax.)
In this first example, we gather data from a built-in random number
generator. This gives a value between 0 and 1. We then just report it
in a popup window, using the alert()
function. Note that
your book always uses window.alert()
, but these are the
same thing in every browser that we are aware of, so we will use the
shorter name.
In this second example, we process the number by multiplying it by 6, rounding the value down, and then adding 1. The result is a random number from 1 to 6, which might be a useful replacement for rolling dice.
Random numbers are useful because we can use them to vary the content
of our pages, say by showing a random image on the home page, or
choosing a quote of the day
or a testimonial, or ...
Here, we gather data in the form of the user's name, then we compute a response string by gluing their name onto the end of a common greeting, and finally output the result with a popup window.
We would probably never do this greeting in a real website, but someone's name could be filled into a form, added to a roster, guest list or signup sheet, emailed to someone, ...
This is almost the same, but we tell them the length of their name.
Again, not useful in itself, but it's nice to know that we can find out the length of a string. For example, we can limit the length of people's posts in an application like a Facebook wall.
Here, we ask for a number and use it in a calculation.
Finally, we've gotten to something that's almost useful. Imagine a website where you're asking for data in metric units, but you know that's a mental hazard for some Americans, so you provide a little conversion calculator.
Here, we gather numbers using a form and report the result using the same form. We have two buttons to do two conversions. You can also use the code boxes.
Here, we ask for two strings, and then compute the first possible Wellesley username for this person, following the rule of first letter + lastname up to 7 letters.
Here, we ask for the person's name, quest and favorite color. We then modify the following box:
In the following sections, we'll get a first look at various facets of the language. Here's more to say about all of these, but this brief tour will help you see how these different aspects of the language fit together. After all, when you learn a natural language (e.g. French or Chinese), you don't try to learn all the verbs first, before tackling any of the nouns or adjectives.
Variables are just named storage locations for a program. We used them
in the examples above to store stuff that we computed (such as random
numbers) or stuff that came from the user (such as their name or height)
or stuff that we computed based on those values (such as their height in
centimeters). The technical name for stuff
might be data
or value
.
You can put a value into a variable, using an assignment statement, like these examples:
var name = "Harry Potter"; var lbs = 150;
Note that this use of the equals sign is very different from
how it is used in mathematics. In math, the equals sign is an assertion
that two things have the same value. In computer science, the equals
sign means Put the value on the right into the storage location on
the left
. (Yes, this is confusing. Some programming languages use
a different symbol, but most use the equals sign.)
Because the equals sign doesn't mean equality, we often pronounce it
differently. Instead of saying lbs equals 150
, we
say lbs gets 150,
short for gets assigned the
value
.
After it has been assigned to, the value can be retrieved and used just
by giving the name of the variable. For example, the following two
statements use the values of name
and lbs
and the assign two new variables
called len
and kg
.
var len = name.length; var kg = lbs*2.2;
Stay tuned for more details on variables
The first few examples accomplished the reporting of the
response by use of the alert()
function. It looked like
this:
alert(response);
This built-in function will pop up a window that displays whatever
value is supplied to the alert()
function by placing it in
the parentheses. In this case, it reported the value that was in the
variable named response
. In later examples, we
saw alert()
with an expression inside the parentheses. This
expression is evaluated and then alert()
reports the
result.
Alerts are annoying in working code, but they are very useful when testing and developing code, because they stop the execution of the program until you acknowledge them:
A statement like alert("foo")
is an example of a
function call or function invocation,
where alert
is the name of a standard JavaScript function and
the expression in parentheses (in this case, "foo"
) is
the argument of (that is, input to
) the function.
Very similar to alert()
but much less annoying
is console.log()
. It's used in almost exactly the same way:
you put a value (or a variable containing a value) into the parentheses,
and that value gets reported. However, the difference is
that alert()
demands that the user acknowledge it,
while console.log
writes it to a hidden place that only web
developers know about, and keeps going, so the user is not annoyed or
delayed by the message.
The console is also where the browser writes error messages. It writes them there so that the muggles won't see them and worry about them, but the wizards and witches of the web (such as yourselves) can easily see them. As of this writing, here's how you can find them:
Try it! Click the button below to execute those
two console.log
statements and then look for them in the
console of your current browser.
We will use console.log
and alert
a lot as a
way of getting some insight into what our code is doing and to help
understand it and debug it. So it's worth becoming comfortable with
finding and looking at the console.
Many JavaScript books and websites, as well as past offerings of CS110,
used document.write()
as a way of putting dynamic content
into a web page. It still has its place, but in CS110 this semester, we
will be eschewing document.write
in favor of a modern
approach using jQuery. So, you can safely ignore it. If you see
examples of its use in our notes, let us know so we can expunge it.
You can (and should) add comments to your JavaScript code. As shown in the example below, JavaScript supports two kinds of comments:
/*
and ending with */
that may span several lines.
(This is the same form as a CSS comment.)
//
and goes to the end of the line.
<script type = "text/javascript"> /* (Block Comment) Pop up an alert box with a message making sure that you all are awake because at this time of day, you might be sleepy. Of course, a lot of it depends on what you were doing last night... */ alert("Hey you there -- wake up!"); // (Line Comment) The user must be awake if we reach this point! console.log("User has woken up"); </script>
We saw several occurrences of line comments in the examples, as a way
to comment out
a line of code that we didn't want to run, because
it was an example or test value.
JavaScript programs manipulate values. The two basic kinds of values we've seen today are:
"
) or
the single quote character ('
):
"Harry Potter" 'grail'
An expression is a JavaScript phrase that
denotes a value. The simplest numeric expression
is a number itself. We can also create more complex numeric
expressions using the numeric operators
+
, -
, *
, /
and %
:
Expression | Value |
---|---|
27 |
27 |
27 + 10 |
37 |
27 - 10 |
17 |
27 * 10 |
270 |
27 / 10 |
2.7 |
27 % 10 |
7 |
The % operator is the remainder or modulus operator. Its value is the remainder when the first number is divided by the second. We saw it in the example when converting centimeters to feet and inches. An average size woman might be 64 inches tall. To find the number of feet, we divide 64 by 12 and round down, to get 5. To get the number of leftover inches, we divide 64 by 12 and take the remainder, using the % operator. That gives us the 4. The remainder operator is more useful than you might think. But don't worry about it; you can think of it as a weird kind of division.
For the most part, JavaScript follows the
algebraic precedence
rules that you learned in school years ago, often with a mnemonic
like Please Excuse My Dear Aunt Sally
or PEMDAS
or
something. That just says:
JavaScript follows these rules, so your prior experience will serve as
a good guide. There are a few new operators that you'll learn, such as
the %
or remainder operator, also called
the modulus operator, which has, unsurprisingly, the same
precedence as division.
Try to guess what the following will evaluate to:
Expressions can be organized into trees of operations that can be arbitrarily complex. For example, the expression denotes a tree of numeric operations:
((3 * 5) + (8 / 4)) - (9 % 2)
The process of determining the value of an expression is called evaluation. Expressions are evaluated as you'd expect, starting at the leaves of the tree and working left to right, combining branches until only one value remains. Here are the evaluation steps for our example:
((3 * 5) + (8 / 4)) - (9 % 2) => ( 15 + (8 / 4)) - (9 % 2) => ( 15 + 2 ) - (9 % 2) => 17 - (9 % 2) => 17 - 1 => 16
The arguments to functions and methods like alert()
and document.write()
can be arbitrary expressions.
This provides an easy way to test expression evaluation:
Literal strings can be denoted by either single or double quotes, which gives you some flexibility about how to handle awkward situations such as quotation marks inside a string:
Expression | Value |
---|---|
"Let's play Tag!" |
Let's play Tag! |
'Not "it"!' |
Not "it"! |
These examples show that you can put a single quote inside double quotes and a double quote inside single quotes.
The main operation on strings is the concatenation
operator, +
:
Expression | Value |
---|---|
"CS" + "110" + " rocks!" |
CS110 rocks! |
"Harry" + "Cho" |
HarryCho |
We saw this many times in the examples, as we created our response text out of literal strings, values supplied by the user, and computations from them.
We'll see that there are many situations where it's necessary to
convert from a string of digits to numbers. The
parseInt()
and
parseFloat()
functions are used for this purpose. We saw that in the examples when
we prompted the user for a number that we wanted to compute with.
Expression | Value |
---|---|
parseInt("243",10) |
243 |
parseInt("cs110",10) |
NaN (Not a Number) |
parseFloat("3.141") |
3.141 |
parseInt("3.141",10) |
3 |
The second argument to parseInt
is the radix
or base
that you want to use. It can be 10 for decimal
number, 16 for hexadecimal numbers and 8 for octal numbers (base 8).
It's a good idea to supply this value, to avoid JavaScript inadvertently
doing the wrong thing.
You can test any of the above expressions here:
Like alert()
, invoking the prompt()
function
pops up a small window, but (1) it also allows the user to type in a
string and (2) the string entered by the user is returned as the value of
invoking the prompt()
function.
Warning: The prompt()
function does not work properly
in certain browsers, especially some versions of Internet Explorer. So
it's best not to use it in projects. We will use forms instead, which are
much better. However, prompt()
is helpful for teaching
certain aspects of JavaScript in an interactive setting, so we will use it
in class for examples.
For example, the following statement prompts the user for a first name and then stores it in a variable.
The result of invoking the prompt()
function is always a
string, NOT a number, even if it's all digits, so it's necessary
to use
parseInt()
or parseFloat()
to convert sequences
of digits entered by the user to numbers. Compare the following two
examples:
In this example, we convert the strings into numbers, then add the numbers and report the result.
Note that if we never need the strings a
and b
, we can take the value of prompt
and
immediately convert it to a number using parseInt
:
The first argument of the prompt()
function is displayed
above the input area of the prompt box.
The prompt()
function takes an optional second argument
that, if supplied, is used as a default value for the input area.
For example:
Using a default value makes it easier on the user when the default is right, but let's him or her correct (override) the value when it's wrong.
Let's take a moment to revisit our general approach to computing, namely the gather/compute/report sequence.
We've seen a variety of ways to gather data:
testvalues, as we saw.
We've also seen a variety of ways to report the data:
alert()
to put the result in front of the user,
though this is intrusive in practice and should usually be avoided in
finished code.
text()
method. We saw an example of this in the
homage to Monty Python. Don't worry about the
details of this for now. We'll learn how to do this very soon.
document.write()
to put the result
into the page that is being built, but we won't do that.)
Computing generally seems to always consist of a sequence of steps in which new variables are assigned values computed from earlier variables. This won't always be the case, but it's a reasonable approximation for now.
Now that we have a general idea of these computing concepts, and we've seen some examples, let's dig into them in more detail.
We will learn more about using jQuery later, but let's learn one fairly simple but powerful thing, just to get our feet wet.
First, remember you always have to load the jQuery library using the incantation we saw above. Here it is again:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
Loading that library creates a variable called jQuery
. It also
creates a shorthand of the jQuery
variable whose name is the dollar
sign ($). Everything we do using jQuery will start with a dollar sign.
The following HTML/CSS code creates an empty, green-bordered box on the
page, whose ID is pandora
.
<div id="pandora"></div> <style> #pandora { width: 50%; margin: 0 auto; border: 2px solid green; padding: 5px; } <style>
Suppose we wanted to put some text dynamically into it. The following lines of JavaScript do the trick:
Try putting hope
into the box instead.
Let's try to understand this example of jQuery code. (Remember, jQuery is an extension of JavaScript, not a whole different language, but it can seem like a different language at times.) Here it is, with fancy color highlighting:
var contents = prompt("What to put in Pandora's box?", "all evils"); console.log("putting "+contents+" into Pandora's box"); $('#pandora').text(contents);
The first two lines of code are things we have seen
before: prompt()
gets a string from the user and the first
statement stores that string in a variable
called contents
. The second line glues a few strings together
(some of which are string literals and one of which is in
the contents
variable) and then writes the combined string
onto the console log.
The third line puts the string into the box, using a jQuery incantation:
$(#pandora).text(contents);
How does the incantation work? There are basically three things going on here:
$(selector).method(stuff);
pandora
. Hence it uses #pandora
, exactly
like the CSS does. Thus, all your skills with selecting elements using
CSS will serve you well when using jQuery.
.text()
method replaces the contents of all the
elements that were chosen by the selector (in this case, just one).
So, in summary, we used jQuery to find the div and insert the user's input into it. What we haven't shown you is how to trigger this behavior in a more elegant way than one of these execution boxes. That will have to wait for a later lecture. Be patient.
However, believe it or not, you now know enough JavaScript to do the first homework assignment! Nevertheless, let's also see another example.
In general, one use of JavaScript is adding dynamic behavior to a page that would otherwise be static. For example, we could allow a user to add items to a grocery list:
Note: This list isn't saved anywhere; it's like Firebug: it
just lives in your browser. In a much later lecture on Ajax, we'll learn how to
save these to a database. Before then, we'll learn how to create an add
item
button.
First, you'll notice that there was already a list on the page, consisting
just of the item apples.
That was done like this:
<ol id="groceries"> <li>Apples </ol>
Notice that there is an id on this grocery list. That's because we'll want to choose it (distinguishing it from all the other OL elements that might be on this page).
As before, the jQuery code for adding to the list is very compact:
$(#groceries).append('<li>'+item);
How does it work? There are the same three things going on here as in the Pandora's box example.
$(selector).method(stuff);
groceries
.
Another example of adding dynamic behavior to a page that would
otherwise be static is tabs
, which we also saw on the first day of
class. They look like this:
Sorry, you got a goat
Sorry, this door also hides a goat
Yay!! You win the prize!
To use tabs in jQuery is a bit more complicated than adding to a grocery list, but it's not too bad.
First, in addition to loading the jQuery library, we also have to load the jQuery UI (user interface) library and some CSS. So, we add the following to our document. Note that you have to load the jQuery UI after you load the jQuery library, because the UI library depends on the jQuery library.
Put this at the foot of your page, right after
the <script>
that loads jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
You could put the following <link>
anywhere, but you
might as well put it either in the head
where your other CSS
is, or in the foot, with the jQuery and jQuery UI code.
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/themes/base/jquery-ui.css">
Second, we have to create some HTML that meets the expectations of
the tabs
method, namely a DIV that contains a UL with
hyperlinks to DIVs that are inside the outer DIV. That looks like this:
<div id="doors"> <ul> <li><a href="#door1">Door #1</a> <li><a href="#door2">Door #2</a> <li><a href="#door3">Door #3</a> </ul> <div id="door1"> <h3>Goat</h3> <p>Sorry, you got a goat </div> <div id="door2"> <h3>Goat</h3> <p>Sorry, this door also hides a goat </div> <div id="door3"> <h3>Prize!</h3> <p>Yay!! You win the prize! </div> </div>
Finally, we invoke the tabs()
method of jQuery, applying
it to the item whose id is doors
. The
following <script>
element goes in the foot, after
loading jQuery and jQuery UI.
<script> $('#doors').tabs(); </script>
You'll notice that the code pattern is very similar to what we saw with appending to a shopping list:
doors
. (We
could have called it something else, of course.)
So, in summary, to use tabs, we just (1) load the jQuery UI and CSS in addition to jQuery itself, (2) set up the HTML, and (3) activate the tabs behavior. Here, you really have all the code necessary to implement this very cool JavaScript behavior. (There are some improvements we'll learn later, but this will work.)
Here is a complete, self-contained example of the tabs behavior. Try it out and look at the source code. Here is the exact same HTML tabs code, only without turning on the tabs behavior. It's important to make sure that your website still works for those without JavaScript.
In the homage to Monty Python, the text was
inserted into the current document without
using document.write
. That turns out to be a much better
technique, since document.write
can only be used
when the page is being built (loaded) and not afterwards. This is why we
are avoiding document.write
and only using jQuery.
Let's learn how to use this technique. There are two steps:
.text()
if the content you want to insert is simple
text,
.html()
if the content you want to insert is
general HTML, and
.append()
if we want to add the new content onto
existing structures.
There are other (many other) jQuery methods we could use, but this will get us started.
Here's an example. The follow box is a div whose ID is 'feedback':
The following execution box has some JavaScript code that allows you to modify the contents of the box dynamically. Notice the jquery pattern we've seen before:
$(selector).method(stuff);
Modify the content string and try to insert other stuff!
Here's the same idea, but with prompt
and inserting the
text in several places using IDs and CSS classes as selectors
(descendent selectors). The following box has an id of "story" and
two span
elements of class gift
.
<div id="story" style="border: 2px solid green; padding: 3px 1em;">For Xmas, my wife got me a <span class="gift">noun</span> and I got her a <span class="gift">noun</span> too!</div>
Now, ask the user for some content to insert:
As we've seen, the purpose of a variable in any
programming language, including Javascript, is to remember
a value
so that it can be used later. It can be useful to think of a variable as
a named box that can store a single value. We can then access the
contents of the box by referring to the name of the variable.
In JavaScript we create a new box with
name variable-name
that
holds the value
of expression
using a
variable declaration that looks like this:
varvariable-name
=expression
;
For example:
var ron_age = 17;
17
ron_agevar ginny_age = ron_age - 1;
17
ron_age
16
ginny_age
The value stored in a variable may be any JavaScript value, for example, it could be a number or a string. The contents of a variable box can be used later in the program by using the name of the variable. For example:
Variables are particularly helpful because they provide a way to name the values typed in by a user so that we can use the entered value later:
Notes:
current_age
is a much better variable name than
x
. It is also a very good practice to use
underscores or alternating case (a.k.a. "CamelCase")
to make it easier to read variables whose names have
multiple words. For example:
underscores | camelCase |
---|---|
current_age |
currentAge |
sum_to_date |
sumToDate |
temp_in_Fahrenheit |
tempInFahrenheit |
expenses_year_2002 |
expensesYear2002 |
var
, input
, form
,
class
, function
, if
,
document
and lots more. Right now, you don't know
what all these terms mean — we will learn about them in
upcoming lectures. In the meantime, if you are having problems
with a variable and you can't figure out what is wrong, you may be
running into such a problem. Try renaming the variable and see if
that helps. Here's a complete list
of JavaScript
reserved words.
alert
or prompt
, but that would destroy the existing
definitions of those functions, so don't do that.
sum
, Sum
, and SUM
each
represent different variables.
=
is
pronounced gets,not "equals". So "var x = 5" is pronounced "var x gets five". Using "gets" emphasizes that the variable box is "getting" a new value. We avoid "equals" because in mathematics it implies that the value never changes, but we'll see below that the values of variables can change over time. (Why do you think they're called "vary"ables?)
You can type JavaScript code into the Execution Box below and execute it. Try the following statements, computing the cost of getting ready for the first day at Hogwarts.
Remember that Hagrid states: The gold ones are Galleons. Seventeen
silver Sickles to a Galleon and twenty-nine Knuts to a Sickle, it's easy
enough.
(See Harry Potter
Lexicon.)
var books = 5 * 4; // five books at 4 sickles each var cauldron = 2; // one cauldron is 2 galleons even var subtotal = cauldron * 17 + books; // in sickles var tax = Math.round(subtotal * 0.15); // even wizards pay tax var total = subtotal + tax; var galleons = Math.floor(total / 17); var sickles = total % 17; var ron_cost = "Ron spent "+galleons+" galleons "+ "and "+sickles+" sickles";
For each line, type in the line and an alert()
command
with the appropriate variable to show the value. Before you evaluate each
thing, see if you can predict what will show up in the alert box.
Errors in programs are usually known as bugs and getting rid
of them is known as debugging.
There are several kinds of
bugs, such as syntax errors (the browser didn't understand what
you said, probably due to some typo) and logic errors (the code
runs to completion, but computes the wrong answer). Let's look briefly at
a few syntax errors and the messages they produce. To learn more about debugging JavaScript,
please consult our lengthy essay on the topic.
Your main tools for debugging are (1) the error console and (2) Firebug or its equivalent. Every browser has an error console (though some hide it better than others). In Firefox, you'll usually find it on the Tools menu. Make sure you can find it. Refer to it often when you're debugging JavaScript.
The following snippets of JavaScript code contain errors. Copy/paste them into the execution box, execute them, and consult the error console so that you can see the error messages. Or, copy/paste them into Firebug or the equivalent.
alert("Hello out there in user land!); alert("I wonder how long the message in an alert box can be? Is it possible to print too much stuff if I just run on and on?"); alert('It's fun making errors on purpose!'); alert(bugs are not fun); alert(this is cool); alert(3 * 5%); alert(weird); Alert("Hi!");
The following formula can be used to convert a temperature in degrees Fahrenheit to Celsius. This would be the middle step of a three-step gather/compute/report computation to convert temperature readings.
var temp_in_Celsius = (5 / 9) * (temp_in_Fahr - 32);
Use this in a JavaScript program consisting of three statements:
temp_in_Fahr
alert()
statement that reports the converted temperature. Make
the alert()
nice and descriptive, like this:
You entered 32 degrees Fahrenheit. That's equivalent to 0 degrees Celsius.
Use your code to convert each of the following temperatures from Fahrenheit to Celsius, and report the corresponding temperatures.
If you're feeling ambitious, insert the sentence into the following box, whose id is "box_f2c":
What value of Fahrenheit is the same as the value in Celsius?
Copy the following skeleton code into a new HTML document that you create
with TextWrangler, and insert your JavaScript code into the body of the
document. Remember to include the <script type="text/JavaScript">
and </script>
tags!
<html> <!-- Wendy Wellesley cs110 9/21/01 --> <!-- Converts a temperature from Fahrenheit to Celsius --> <head> <title> Fahrenheit to Celsius </title> </head> <body> </body> </html>
Please don't skip these sections. These pitfalls crop up all the time, and you'll save yourself lots of head-scratching, hair-pulling, and other signs of frustration if you read over these, particularly re-reading them when you run into difficulties.
Programmers frequently use comments to comment out
a block of
code that (they suspect) isn't working right or they just want to have
the JS engine skip. Thus:
<script type = "text/javascript">
/* Comment out the following:
/* The following is supposed to make the program intelligent,
but it's not working yet. */
think(deeply);
You might think this is part of the outer comment, but it's not,
since the outer comment ended above! */
alert("Done thinking");
</script>
Sadly, as in CSS, block comments do not nest properly, which causes great pain.
A pox on language designers who do not support nested block comments!
In the section on Strings, we said that you
could use either single or double quotes, and that helps with embedding
the other kind of quote. But what if you have both? In that case,
where the one-inside-the-other trick doesn't work, you can use a
backslash character to have a quotation mark treated as an ordinary
character, instead of one that ends a string. (Technically, this is
called an escape
character, since the character escapes
from its usual interpretation. We saw this above with the backslash
preceding a slash in the HTML in a document.write()
.)
'You\'re "it"!' |
You're "it"! |
"You're \"it\"!" |
You're "it"! |
Try it:
One unfortunate limitation of string literals (text in quotation marks)
in JavaScript is that they can't cross line boundaries. For example,
try the following. You won't get the alert. Instead, you'll get an
error about an unterminated string literal
(check the error
console).
Please understand that there's no limit on the length of a string, short of running out of computer memory. This is only a limitation on line breaks within the quotation marks.
But what if we want to have a long quotation like the above? How to
handle that? The easiest thing is to do it to break it into one-line
chunks and then use the concatenation operator (+
) to glue
them together:
The expression 3+4 evaluates to 7, because the +
operator
means to add. The expression "three"+"four" evaluates to
"threefour" not "seven", because the +
operator means
to concatenate.
The fact that the +
operator means different things for
numbers and strings is a source of confusion and bugs in JavaScript
programs. This is made worse by the fact that any attempt to add
a
number and a string in JavaScript succeeds by first automatically
converting the number to a string of digits:
Expression | Value |
---|---|
"foo" + 27 |
"foo27" |
10 + "bar" |
"10bar" |
"foo" + 27 + "bar" + 10 |
"foo27bar10" |
"foo" + 27 + 10 |
"foo2710" |
"foo" + (27 + 10) |
"foo37" |
27 + 10 + "foo" |
"37foo" |
27 + (10 + "foo") |
"2710foo" |
"" + 27 + 10 + "foo" |
"2710foo" |
You can test any of the above expressions here:
Here's a realistic example, where we try to add one to someone's age. Before you click the button, guess what the value will be. Then see if you are right.
If this weren't confusing enough already, it turns out that for
arithmetic operators other than +
, JavaScript
will automatically convert strings of digits to numbers!
Expression | Value |
---|---|
"27" + "10" |
"2710" |
"27" * "10" |
270 |
"27" / "10" |
2.7 |
"27" % "10" |
7 |
You can test any of the above expressions here:
JavaScript is case-sensitive, which means that lower-case and upper-case versions of a character are treated differently in function, method, and variable names.
Alert("foo")
or ALERT("foo")
in place of alert("foo")
.
document.Write()
and Document.write()
are
not the same thing as document.write()
.
Only the last one works.
Sum
, you can't later try to
refer to it as sum
or SUM
.
We have already explained that JavaScript statements are executed in order from top to bottom, and individual statements are executed from left to right. However, the order of operations still applies, which means that nested expressions are evaluated first, even if they are not on the left side of the statement.
For example, consider the expression:
3 * (4 - 2)
We know from learning algebra that the expression inside the
parentheses (4-2)
is evaluated first, even though it appears
on the right. The res ult of that expression (2) is then multiplied by 3.
Another way to think of the expression above is to treat the multiplication and subtraction operators as functions:
multiply(3, subtract(4,2))
In this case, the subtract(4,2) function is evaluated, and its result is then passed to the multiply function as an argument.
Now consider a JavaScript statment that includes a nested function call:
alert("Hi " + prompt("What's your name?"))
The prompt()
function is executed first, because it is
nested inside the alert()
function. Next, the
string Hi
is concatenated with the value returned by
the prompt()
function. Finally, the concatenated string is
passed to the alert()
function, which is evaluated last.
While we have been conditioned to respect order of operations when dealing with numbers, it is easy to forget that the same rules still apply when writing code that includes nested functions.