For diving deeper into JavaScript, please read Chapter 1 of 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 this course: 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).
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 View > Developer > Javascript Console menu item.
Anything interesting there? (Ignore the complaint abour Google code prettify.)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 off to the nearest integer. And you can. If you were to compute
Math.round(59.090909090909086)
you would get the result 59. Can you find a way to
put the Math.round
calculation in the code above, so that it gives you a
rounded value in the alert window. (That's hard at this stage of your learning.)
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%; }
OK, here is the javascript code that will change the box above:
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.
Here is the code:
<button id="greeter1" type="button" onclick="alert('hi there!');">Greet me</button>
Notice the JS code in the onclick
attribute; there
are also other attributes where JS code can be put.
<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 good practice is to put the code just before
the closing tag for body
. Here is an example:
<body> ... <button id="greeter2" type="button"">Greet me</button> ... <script> function sayHello() { alert('hello!!'); } $("#greeter2").click(sayHello); </script> </body>
In the preceding, you'll see that the button has no JavaScript
code at all; the code is in the script
tag. However,
there's a slightly more elaborate mechanism for defining and
attaching the code. We'll get to these later in the course.
script
element above would go in
a separate file and we simply load it using an alternative form
of the script
tag. Here is an example:
<script src="myJScode.js"> </script>
We'll be using all three ways in our examples, but like with CSS, if you were creating a larger website, you should avoid inline JS. You should use mostly external JS (when shared across pages) and document-level JS.
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 weight = 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 that you see on the right of the equals sign into the storage location that is mentioned on the left of the equal sign.
Because the equals sign doesn't mean equality, we often pronounce it
differently. Instead of saying weight equals 150
, we
say weight gets 150,
short for gets assigned the
value
.
After a variable has been assigned a value, 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 weight
, 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 = weight/2.2;
We will return to the concept of variables in future lectures.
alert()
FunctionThe 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 earlier 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:
Some terminology: 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. We'll learn more about functions later, but
knowing alert()
is useful right away.
console.log()
FunctionVery 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. 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 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" + "115" + " rocks!" |
CS115 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. Concatenation is also useful for splitting strings across multiple lines. Let's say we want to display a string that represents a table. If we try to fit it in one line, it may look something like:
alert("id,name,age,height(ft),0,Amy,5,4,1,Ben,9,6,2,Cindy,5,5");
With all of those numbers, it can be hard to parse the information when reading the code. Unfortunately, we can't jump to the next line in the middle of a string, but we can use concatenation:
alert("id,name,age,height(ft)," + "0,Amy,5,4," + "1,Ben,9,6," + "2,Cindy,5,5");
parseInt()
and parseFloat()
FunctionsWe'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 numbers with a fractional part (after the
decimal point).
The function takes an (optional) second parameter that says what number base to use. We'll typically use 10 for decimal numbers.
Expression | Value |
---|---|
parseInt("243",10) |
243 |
parseInt("cs115",10) |
NaN (Not a Number) |
parseInt("3.141",10) |
3 |
parseFloat("3.141") |
3.141 |
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:
prompt()
FunctionLike 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.
For example, the following statement prompts the user for a first name and then stores it in a variable.
The prompt()
method is not the best way to get input in Javascript but it is OK for now. Better ways are to use HTML forms,
or the jQuery library, but we can ignore it for now.
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.
prompt()
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 to numbers. Compare the following two examples:
In this first example, we just use the +
operator on the
strings returned by prompt()
:
However, in this example, we first convert the strings into numbers (a
float for the first, and an integer for the second), then apply
the +
operator:
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
, so the
second example can be written more succinctly like this:
You have already learned a lot of JavaScript. For diving deeper, please read Chapter 1 of the book Head First Javascript Programming.