Concepts in Computing
CS4 - Winter 2007
Instructor: Fabio Pellacini

Lecture 9: Intro to JavaScript

Overview

  • What is JavaScript?
  • Examples
  • Basic JavaScript syntax
  • Including JavaScript in HTML

Introduction to JavaScript

JavaScript is a computer programming language. Programming languages are used to tell computers how to execute algorithms, in contrast to markup languages such as HTML, which are used to describe the structure of a document to a computer. You've already written algorithms in a vary similar pseudo-code; now we will investigate how to instruct a real computer how to process an algorithm, in the JavaScript language.

There are many, many different programming languages out there (see a fun illustration of that). One important part of a language is how we construct "sentences". The syntax gives the set of rules determining what's grammatically correct. Programming languages are much pickier than HTML, and perhaps even your writing teachers. For example, whereas a browser simply ignores tags that it doesn't understand, if you give JavaScript something it doesn't understand, it simply won't work, and will give you an error message.

Another important part of a language is how we understand what a program means. The semantics defines the meanings of language constructs. For example, we need to understand not only how a loop is written (use the word "while", etc.), but precisely what it will do (perform the test, then the body only if the test is true, etc.). Similarly, we must understand what the "+" symbol computes (and as we'll see, it's not just for addition of numbers). As with human languages, different programming languages can make you think differently.

Some examples

JavaScript syntax

Important Note. Up to this point, we have been using HTML, which is not case sensitive. That is, it does not care whether you use upper or lower case in your tag and attribute names. JavaScript, however, like most programming languages, does care about case. It is very important to keep this in mind when using HTML and JavaScript together in your documents.

We'll cover these parts of JavaScript syntax:

  • Variables
    • Naming
    • Declaring
    • Assigning
    • Types
  • Basic expressions
    • Expressions and values
    • Basic arithmetic expressions
    • Variable names vs. variable values
  • Decision making
    • Boolean expressions
    • Logical operators
  • Functions
    • Parameters and Arguments
    • Calling
    • Defining

Variables

A variable is a named storage location in a computer's memory. By now you're familiar with the use of variables in your own algorithms; the same basic concept applies in JavaScript as well. The important things to remember is that a variable has a name, as well as a value. Since there are many storage locations within the computer, it is important that each variable have a unique name. On the other hand, each variable may have any value that makes sense, and the values of different variables may be the same.

A variable name must begin with a letter, and may consist of letters, digits (0, 1, 2, ..., 9) and underscores (_). Here are a few examples of valid variable names:

  • i
  • examGrade
  • my_long_variable_name

As stated above, variable names are case-sensitive!. This means that the name examGrade is considered a different name from EXAMgrade or examgrade, even though they have the same letters in them.

Generally speaking, you can use any name you like for a variable, so long as it doesn't conflict with a small set of "keywords" that are defined by the JavaScript language. Keywords are names which are reserved by the definition of the language, and can't be used for variable names. Examples in JavaScript include var and new.

Declaring variables

Before you can use a new variable name, you need to tell JavaScript that you want that name to be a variable. To do this, you declare the variable using the var keyword. To declare a new variable named examGrade, you would write:


  var examGrade;

JavaScript uses the semicolon to mark the end of individual statements. Statements end in semicolons because whitespace -- including spaces, tabs, and line-feeds -- is usually ignored by JavaScript. So, for example, we could have written the above as:


  var 
    examGrade    ;

Unless a variable name is already provided for you (there are a number of variable names that are built-in to JavaScript), you need to declare each variable name before you use it. If you want to declare several varable names at once, you can do so with a single var statement, by separating a list of names with commas:


    var examGrade1, examGrade2, examGrade3;

This has the same effect as if you had written:


  var examGrade1;
  var examGrade2;
  var examGrade3;  

Assigning values to variables

Once you have declared a variable, you want to store a value into the variable's memory location. Associating a value with a variable is called assignment. In JavaScript, we use the equals-sign (=) to indicate assignment: The name of a variable goes on the left, and the new value goes on the right. For example:


  examGrade = 96;

You can combine the declaration of a new variable with assignment, by putting them together in somewhat obvious fashion:


  var examGrade = 96;

This code accomplishes the same task as if you had written the declaration and the assignment as separate statements, as in:


  var examGrade;
  examGrade = 96;

Variables, Objects, and Types of Data

Variables can hold many different kinds of data. In the above examples, for instance, we stored the number 96 into a variable called examGrade. As we saw in one of the code examples, we distinguish "integer" numbers (that can't have anything after a decimal point) from "floating point" numbers (that can). We also saw "strings", which are just sequences of printable characters. There are also logical (Boolean) values like "true" or "false", and arrays (like the ones we used in our sorting algorithms, for example). No matter what type of data you are dealing with, however, it is represented in the computer's memory by a construct called an "object", which is really nothing more than a blob of binary information representing the data you are considering.

Later this term, we will begin to look at just exactly how some of these objects are represented in the computer's memory; however, for the time being, it's sufficient to understand that an "object" is just a computer's way of representing some piece of data.

In addition to numbers, strings, Boolean values, and arrays, there are many other types of objects that a JavaScript program can interact with. We will only consider a few of these; however, the important thing to note is that each individual object has a "type" associated with it, and the type of an object determines what it looks like, what attributes it has, and what kinds of operations can be performed on it.

Variables and the Document Object Model (DOM)

JavaScript is closely associated with HTML, and can get input from and modify an HTML document. This interconnection relies on the document object model (DOM). You can view the DOM using the "DOM Inspector" in Firefox. The DOM determines how names are assigned to the various pieces of your document, and thus how JavaScript can access them.

The document object model has a hierarchical structure, wherein each component of the structure "contains" other pieces inside it. So, for example, there is a "document" object that represents your HTML document. That object contains "form" objects, that represent the forms you have defined, "link" objects representing hyperlinks, "anchor" objects representing the anchors, "image" objects representing the images, and so forth.

Furthermore, each of these other objects contains other objects, which represent the pieces of that object. For example, a "form" contains objects representing each of the input elements you have defined in that form. Each of these objects has various attributes like "name" and "value" that let you figure out what the current state of the input element is.

This relationship is illustrated in the following diagram:

DOM Snapshot

To identify a particular object in this hierarchical structure, you need to give a list of names that traces a path down from the top of the tree to the object you are interested in. In JavaScript, this is done by giving a sequence of variable names separated by period (.) characters (usually called "dot" for short):


  document.myForm.textField.value

This "dot notation" is one of the central concepts in JavaScript, which you will use extensively in your programs, so it's important to understand this now. Each component of a dotted variable name is an individual variable name, which identifies a storage location "belonging" to the previous variable in the list. For the first variable on the list, JavaScript has pre-defined several variables for you, such as the "document" variable, which you we used in the code examples.

Firefox has a "DOM Inspector" feature that permits you to see an outline of a document's object model. To view this, go to the Tools menu and select "DOM Inspector". The window that pops up is similar to the regular browser window -- you enter a URL in the location bar at the top, and press enter. But the DOM Inspector, in addition to displaying the page, also shows you an outline of the whole structure of the document, down to each tag and its attributes.

Basic Expressions

In human languages, we can express an idea in a variety of different ways. For example, all of the following expressions refer to the same underlying concept:

  • "The number of sides in a triangle"
  • "The result of dividing fifteen by five"
  • "Three"

Although each of these three sentences uses different words, they all represent the same basic concept, the number 3. By evaluating each expression, we can find out what each expression refers to. Evaluating "the number of sides in a triangle" means looking up the definition of a triangle, and finding out how many sides it has. Evaluating "the result of dividing fifteen by five" involves performing a simple division problem. Evaluating "three" doesn't take any work at all -- this expression is actually "primitive", in that it doesn't need to be simplified any further to be understood.

The point to be understood here is that there are several ways of expressing computations in a programming language, just as there are in a human language. When we write down a literal integer value, such as 68, we can think of this as an expression that evaluates to the number 68. But of course, there are many other expressions that can be evaluated to get 68, too.

JavaScript permits you to notate most common mathematical operations using the same syntax you would use to write them down on paper. For example, suppose I have three exam grades, e1, e2, and e3, and I want to compute their average. I might write the following JavaScript code:


  var finalGrade = (e1 + e2 + e3) / 3;

This line of code declares a new variable named finalGrade, computes the arithmetic mean (i.e., the average) of e1, e2, and e3, and then stores that value into the variable finalGrade. You can read an expression like this in the same way that you would read it if you were solving the problem on paper. The only thing to note here is that the forward slash (/) means "divide" (that is probably obvious, but is a little different from "standard" mathematical notation).

JavaScript does operations in the same order that they are done in basic arithmetic -- so, multiplication and division are done before addition and subtraction. If you want it to do things in a different order, you can use parentheses (like these) to make it use the order you wanted. The basic mathematical operators understood by JavaScript include + (add), - (subtract), * (multiply), / (divide), and % (remainder). Each of these operators takes two numbers, and yields the result of combining them appropriately (another number).

As we noted above, you assign a value to a variable by writing its name on the left-hand side of an assignment operator (=), and the expression whose value you want to store into that variable goes on the right-hand side. But what if you put a variable on the right-hand side of the assignment, as in:


  var courseName = "CS 4";
  var firstCourse = courseName;

This does what you might expect -- that is, it causes the value stored in courseName, which is the string "CS 4", to be copied into the storage belonging to the variable firstCourse. This underscores the important distinction between the name of a variable and its value -- when you use a variable on the left-hand side of the assignment (=) operator, you are getting its name; when you use it on the right-hand side, you are getting its value.

Decisions, Decisions

In JavaScript, conditionals are written similarly to our pseudo-code. The simplest form of an if-statement looks like this:


  if (examGrade < 20) {
    finalGrade = "E";
  }

The if statement requires that the expression in parentheses have Boolean type. A Boolean value is one that is either "true" or "false" (the name "Boolean" comes from George Boole, an English mathematician who lived from about 1815-1865 and who did a lot of work with the properties of logical values of this type). If the value obtained by your expression is true, then the set of statements inside the braces ({ }) is evaluated. But if it is false, these statements are skipped over.

The most common way to obtain a Boolean (true/false) value is by using comparison operators. In contrast to the arithmetic operators discussed above, comparisons take two values and return either true or false, depending on whether the two values have a certain relationship. For example, the "less-than" operator (<) compares the left-hand value to the right-hand value, and returns true if it's less, false if it's greater or equal. The comparison operators are summarized here:

  • a == b
    If a is equal to b, then true; otherwise false.
  • a != b
    If a is not equal to b, then true; otherwise false.
  • a > b
    If a is greater than b, then true; otherwise false.
  • a >= b
    If a is greater than or equal to b, then true; otherwise false.
  • a < b
    If a is less than b, then true; otherwise false.
  • a <= b
    If a is less than or equal to b, then true; otherwise false.

Notice that the "equals" operator is written as ==, not =, the latter being used for assignment. This is an important distinction! Writing if (a = b) { ... does not mean what you might otherwise expect. In mathematics, we use = interchangeably for assignment and comparison, but computers are not smart enough to know which you mean, so we have two different operators for equality and assignment.

Sometimes, we want to execute different depending on a condition (rather than just skipping on false as previously). In other words, if the condition applies, we do one action, but if it does not apply, we will do some different action. In JavaScript we write this similarly to the first example above:


  if (x > 10) {
    x = x - 1; 
  } else {
    x = x * 2;
  }

Here, the JavaScript keyword else behaves like the word "otherwise" in our pseudo-code. It means, "if the test is false, then do these things instead."

Multiple Decisions: Logical Operators

Often you want to test more than one thing at a time. For example, maybe you want to take a certain action if f is between zero and ten inclusive. To express this in JavaScript, you need a way to say "f is greater than or equal to zero, and f is less than or equal to ten." This "and" operation is written &&:


  if (f >= 0 && f <= 10) {
    // ... some other code
  }

This is called the and operator, and it allows you to combine two Boolean expressions to form a new Boolean expression: the expression a && b is true if and only if a is true and also b is true.

Similarly, it is useful to be able to take a given action based on whether one of several alternatives is true. For example, maybe you want to do something special if finalGrade is "D" or if finalGrade is "E". This can be expressed using the or operator, written as || in JavaScript:


  if (finalGrade == "D" || finalGrade == "E") {
    // ... some other code
  }

Functions

Using variables, you can give names to values in a JavaScript program. It is also possible to associate a name with a sequence of program code. This is called a function. You create functions in JavaScript using the following format:


  function someName() 
  {
    // A sequence of JavaScript statements
  }

What this code does is to create a new function consisting of whatever statements you put between the curly brackets, and associate the name someName with that function. When you want to actually execute the statements, you do so by writing the name of the function, followed by parentheses, like this:


  someName();

The parentheses here tell JavaScript that you're referring to a function named someName, rather than a variable. Wherever you write this statement, JavaScript will perform each of the statements inside the body of the function, as if you had typed them all out longhand. This is called "calling" the function. This behavior can be very useful if you have a bunch of code you want to use again and again in different parts of your program.

When we evaluate an expression, we get back some value. What happens when we evaluate a function? Well, as it turns out, functions can also return values, and this is done by using the return statement:


  return someValue;

In addition to returning a value, functions can also be given values. In fact, we saw that with our pseudo-code algorithms: the Search algorithm was given an array of names and name to look up. We call the values that are given to the function its parameters. For example, suppose we want to write a function that takes three grades as input values, and returns their average. We might write the following:


  function computeAverage(a, b, c) 
  {
    return (a + b + c) / 3;
  }

Having written this, we can now call the function with some specific grade values:


  var finalGrade = computeAverage(86, 92, 75);

The values that you give to the function when you call it are called arguments. The names that you wrote when you were actually defining the function are called parameters.

Local variables

Sometimes a function declares variables to hold information temporarily, while the function is doing its work. Once the function is finished, the variable is no longer needed. For example, consider a function that computes the average grade and converts it to a letter grade:


  function computeGrade(a, b, c) 
  {
    var avg = (a + b + c)/3;
    var grade;
    if (avg > 90) ...
    return grade;
  }

Variables declared inside a function are local, meaning they can only be used inside the function itself. They also only maintain their value while the function is being executed.

Variables declared outside a function are global, meaning they can be used any place in the script. Their values also remain the same over multiple calls of the function. For example, the following code tallies the number of times either function is called.


  var num = 0;

  function f1()
  {
    num = num + 1;
  }

  function f2()
  {
    num = num + 1;
  }

Generally speaking, you should be careful to use a global variable only when necessary; if the information really is only for a single function, during its "lifetime", use a local variable.

You Got Your JavaScript in My HTML!

So, now we have looked at the basic syntax of JavaScript programs, and hopefully you now know enough to look at the examples and understand how the names they are using work, and what kind of computation is going on in them. Now the question becomes, how do we actually tell the web browser what JavaScript code we want to have run?

In HTML, programs are included using the <script> tag. The basic format of the tag looks like this:


  <script language="JavaScript">
  <!--
      ... your JavaScript code goes here ...
  //-->
  </script>

You may be wondering why there are HTML comments surrounding the area where your JavaScript code goes. You might recall that in HTML, if the browser does not understand a tag, it is supposed to ignore the tag -- but it goes on processing the information inside that tag anyway! Old web browsers that don't support the script tag would therefore print out your code right on the web page with your other data. That's ugly and kind of annoying, to say the least. By putting the whole script in an HTML comment, you prevent this from happening, since even the most primitive browsers understand the HTML comment tag. This doesn't keep your program from running, because on browsers that do support the script tag, the portion of the browser that runs your JavaScript code knows enough to ignore the HTML comment tags inside the script tag.

A script tag can also be used to include a script from another file. Just as we used the <link> tag to refer to an external style sheet, the script tag can point to an external script file. To use an external script file, the tag looks like this:


  <script language="JavaScript" src="url">
  </script>

Note that when the src attribute is used, the contents of the script tag are ignored. So, if you are using src to bring in an external script file, you should usually just leave the tag empty.

When does my Script Run?

Generally speaking, your JavaScript code gets run whenever the browser encounters it. The HTML parser reads the document from beginning to end -- so, for example, if you put a script tag into the <head> portion of your HTML document, the browser will run that code before it does anything else with the document. The most common use for this is to set up some functions that can be called later on, while the document is being displayed.

If you put a script tag inside the <body> of your document, it gets run as the browser is rendering (displaying) the page, it reaches the point where the script is located. You can use this fact to modify how the page is drawn, for instance.