In addition to these notes, we suggest that you read Chapter 1 and 2 of the recommended book Javascript & jQuery: The Missing Manual.
If you don't have the book, here is Chapter 1 from the book Head First Javascript Programming.
So far we've learned two languages: HTML and CSS. Today, we start learning the third of the three languages taught in CS110: JavaScript. We will just begin talking about it, so don't worry if you don't understand everything immediately.
JavaScript is a programming language for making dynamic web pages, i.e., pages that can interact with the user and vary each time they are loaded. Although the names are similar, JavaScript is not the same language as Java, which is the programming language used in CS111 (until Spring 2014).
As part of your project you are required to write four distinct JavaScript applications — each student must do two of the four. The four applications must all be different from each other and you will be rewarded for the complexity of these applications. We will also look at how well the applications are integrated into the site — do they fit naturally or are they “tacked on”?
During the upcoming design phase of the project (P2) you must clearly indicate how you and your partner plan to fulfill this JavaScript requirement.
In the lectures to come, you will see plenty of examples of Javascript, that you can use to inspire you to choose applications for your website. You can see some examples of applications that students have implemented for their projects in the Hall of Fame. The last assignment in the semester brings together many of the skills you will learn in the next weeks: generating content dynamically, keeping track of user choices, roll-over effects, jQuery user interface elements, filling and submitting forms. Here is a short screencast of the completed assignment.
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.)
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, ...
var name =
in the first line and execute the code again.
What happens? Can you explain it? What roles are name
and response
playing?
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.
var aName =
in the first line and execute the code again.
Can you explain what happens this time? Open the Inspect Element and switch to the Console tab.
Anything interesting there?Here, we ask for a number and use it in a calculation.
You probably saw a very long number as an answer. For example, the
result for 130, is 59.090909090909086. It would be nice to round it up. And you can.
If you copy the Math.round(59.090909090909086)
in the Inspect Element's Console,
you'll see the result 59. Can you find a way to put Math.round
in the code above, so that
it gives you a rounded value in the prompt window.
Here, we ask for the person's name, quest, and favorite color. We then modify the box below, which was created with the following HTML and CSS:
<div id="grail"> Your name here </div>
#grail { border: 5px solid gray; color: gray; width: 50%; }
Javascript, just like CSS, is a different language from HTML. You might remember that HTML is responsible for defining the structure of a document, CSS for defining its appearance, and Javascript for defining the behavior of a page. Similarly to the way CSS interacts with HTML through inline styles, document-level styles and an external stylesheet, Javascript has the same three ways, but with a different syntax.
Execute it
buttons in the four examples above worked. Here is the code:<button onclick="eval(this.parentNode.firstElementChild.value);">Execute it</button>
<script>
. Differently from CSS, where
the <style>
tag could be only included in the <head>
part of the document, in Javascript you can put <script>
either in
the <head>
or anywhere inside the the <body>
.
A usual practice is to put the code just before the closing tag for body
. Here is an example:<body> ... <p>Mouse over this paragraph to see a cool effect.<p> ... <script> var p = document.querySelector("p"); function hideMe() { this.style.visibility = "hidden";} function showMe() { this.style.visibility = "visible";} p.onmouseover = hideMe; p.onmouseout = showMe; </script> </body>
script
tag. Here is an example:<script src="myJScode.js"> </script>
We'll be using all three ways in our examples, but for your project, you should strive to have all your code in external Javascript files.
In the following sections, we'll get a first look at various facets of the language. There'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 weight in kg)
or stuff that came from the user (such as their name or height).
The technical name for stuff
might be data
or values
.
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
.
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 retrieve the values of name
and lbs
, perform an operation on them, and then assign the
new values to two new variables
called len
and kg
.
var len = name.length; var kg = lbs*2.2;
We will return to the concept of variables in future lectures.
alert()
Statement
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.
console.log()
Statement
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. 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.
You should always add comments to your JavaScript code to explain its purpose. 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> /* (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>
In addition to explaining the code, we can use comments to
to comment out
a line of code that we don't want to run (sometimes when
we are debugging to find where the error lies).
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. Here is an example of when it can be used. 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.
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, which has, unsurprisingly, the same
precedence as division.
Try to guess what the following will evaluate to:
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.
parseInt()
and parseFloat()
Functions
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. The first one is used with integer numbers
and the second one with decimal numbers.
Expression | Value |
---|---|
parseInt("243") |
243 |
parseInt("cs110",10) |
NaN (Not a Number) |
parseFloat("3.141") |
3.141 |
parseInt("3.141") |
3 |
You can test any of the above expressions here:
prompt()
Function
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.
The prompt()
method is not a good use of Javascript and you will
not use it in your projects. Instead we will either use HTML forms,
or the jQuery library.
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 allows him or her to correct (override) the value when it's wrong.