About these notes

For the JavaScript portion of the course I will be producing extensive lecture notes to supplement the material in the textbook. The main reason for this is that I will be introducing material in a slightly different order than the textbook. Also, I will be presenting a set of extended examples meant to introduce important concepts in JavaScript. Each lecture will focus on one example.

At the top of the lecture notes for each of these examples you will see a "quick access" section that provides easy access to the example web page, the source code for that page, the JavaScript source for the example, and a list of suggested reading in the textbook. The first such "quick access" section appears below.

Basic Components of JavaScript

HTML elements for user interaction

The JavaScript language will make it possible for us to program interactive applications in web pages. An important part of interactivity is HTML elements that allow the user to enter input. In the JavaScript example we are going to look at today we will make use of two of these new elements, the text input element and the HTML button element.

Here is what a typical HTML text input element looks like:

<input type="text" class="form-control" id="name" />

I will frequently use Bootstrap to make interactive elements look more attractive: I have applied a special Bootstrap class here for that purpose. A little later in this lecture you will learn the purpose of the id attribute.

A typical HTML button element looks like this:

<button class="btn btn-primary" id="greeting">Greet Me!</button>

The text content in a button element is the text that appears in the button. Also here I have applied a couple of Bootstrap classes to improve the appearance of the button.

Using JavaScript in a Web Page

JavaScript is a programming language that is designed to be run in a browser. To put JavaScript in a web page we typically put JavaScript code in a text file with a .js file extension. To load and execute this JavaScript code we place a script element in the page's HTML code. Today's example consists of two source code files, hello.html and hello.js, that sit in the same folder. To link the JavaScript code into the hello.html web page I placed this element near the bottom of the HTML file:

<script src="hello.js"></script>

As soon as the browser encounters this script element it will open the JavaScript file and load its contents.

JavaScript Variables

All information in a JavaScript program is stored in variables. To use a variable in a JavaScript program we declare the variable by using a variable declaration statement. For example, in the program we will be using as our main example today we need a variable to store a user's name. A variable declaration statement for this particular variable would look like

var name;

The semicolon at the end of the statement is punctuation. JavaScript uses the semicolon to mark the end of a statement in the language.

Declaring a variable does not give it a value. To store a value in the variable we have to follow the variable declaration up with an assignment statement that assigns a value to the variable.

name = 'unknown';

Since the name variable is intended to store text we can initialize it with a JavaScript text string. A text string is a block of text inside quote marks.

As a shortcut you can declare a variable and give it a value all in one statement.

var name = 'unknown';

Variable names in a JavaScript program can contain alphabetic characters (a-z,A-Z), numeric characters (0-9), and the underscore (_) character. Variable names must start with a letter.

JavaScript Comments

All programming languages allow you to insert comments in your code. Comments are helpful for other programmers who may read your code and help to document decisions you made when writing the code or otherwise explain what the code is doing.

As we have already seen, HTML comments take the form

<!--  Comment text goes here -->

Comments in CSS code look like

/* Comment text goes here */

JavaScript can use two styles of comment. A comment that starts with /* and ends with */ is commonly called a multi-line comment, in that it can span several lines of code:

/* I can start the comment on this line
	 and continue it for
	 several lines. */

The second style of comment that JavaScript allows starts with // and runs to the end of the current line.

// Comment text goes here

This second style of comment is often tacked on to the end of a JavaScript statement to document what the statement does.

var name = 'unknown'; // Until I ask, I don't know your name

JavaScript Functions

A JavaScript program typically consists of several functions. A function is a block of code that can be invoked in response to some event.

Here is the structure of a typical JavaScript function definition:

function example() {
	// Statements appear here
}

A function definition starts with the word function, followed by the name of the function. The () after the function name is the parameter list: the simplest functions have no parameters - an empty parameter list looks like (). The body of the function is bounded by a left and right curly brace pair, { }. The body of the function will consist of one or more JavaScript statements. When the function runs, the statements in the body of the function get executed one by one in turn.

The JavaScript DOM

The primary purpose of JavaScript code is to interact with the elements of a HTML page. In a typical bit of JavaScript code we will be reading the content of one or more page elements, doing a computation with those inputs, and then putting the results back into other page elements for display.

To make these interactions possible, JavaScript sets up a document object model, or DOM for short. In the JavaScript DOM every element in the page is represented by a JavaScript software entity called an object. JavaScript objects store data in properties and can respond to commands by executing methods. Our entry point to the DOM is a pair of pre-defined DOM variables, window and document, that give us access to objects representing the window and its contents.

Finding elements

The predefined document variable offers a finding method, getElementById, that we can use to locate objects that represent elements we are interested in interacting with. Here is a typical example. In the main example that goes with todays lecture there is a text input field where the user can enter their name. The HTML code that sets up that element looks like

<input type="text" class="form-control" id="name" />

The most important thing to note here is the id attribute of the text input, name. We will use this id to locate the DOM object that represents this element. To locate and work with this object we start by declaring a variable that will store the object. We then ask the document object to locate the element via its finding method:

var nameField; // A variable that will store a DOM object
nameField = document.getElementById('name');

Interacting with properties of DOM elements

Once we have access to the object that represents the text field we can use its value property to find out what the user typed into the text field:

var name; // Will store the name the user entered
name = nameField.value;

Besides reading object properties, we can also use JavaScript code to set the value of an object property. The most common example of this is setting the text content of a paragraph or a span. In this lecture's example program I set up a paragraph near the bottom of the HTML page that will display the result of the computation. Initially that element looks like this:

<p id="result"></p>

Initially this paragraph is empty. After we run the JavaScript computation that constructs a message, we will insert some text content into this paragraph element. If we had the greeting message stored in a variable greeting we could use the following sequence to make that total appear in that paragraph:

var resultPar = document.getElementById('result');
resultPar.textContent = greeting;

The second statement above sets the text content property of the paragraph. As soon as we do that, that text will appear in the paragraph in the browser.

Event handlers

The last significant aspect of the DOM we will use in today's example is setting up a pair of event handlers. When the user interacts with some element in our page by, say, clicking on a button, the browser will generate an event. In our JavaScript we can express an interest in that event by setting up an event handler. An event handler is simply a function that we attach to some element. When the element generates that event the code in the event handler function runs, giving us an opportunity to respond to the event.

The classic example is responding to a button click event. Today's example contains a single button. The HTML code for that button looks like

<button class="btn btn-primary" id="greeting">Greet Me!</button>

Using some JavaScript code we can locate that button and attach an event handler function to it. That event handler function is the greetingHandler function defined in the JavaScript file. To attach that function to the button we do the following:

var greetingButton = document.getElementById('greeting');
greetingButton.addEventListener('click',greetingHandler,false);

Since elements in a page may potentially generate several different kinds of events, the first parameter to addEventListener is the type of event we want to handle (a click event for a button in this case). The second parameter is the name of the event handler function we want to run when the event happens. The third parameter sets an option for how to further handle the event after running the event handler: this parameter will almost always be set to false. (Should we ever need to specify a different value for this third parameter I will explain in greater detail what this parameter does.)

The example makes use of one other kind of event - the document load event. This is a event that browser will generate for us when the document has finished loading in the browser. By attaching an event handler to this event we can run additional set up code our application will need. To set up an event handler for the document load event we add the following line code to the bottom of our JavaScript code:

window.addEventListener('load',setup,false);

This statement uses the predefined DOM variable window and sets up the function named setup as the load event handler.

The setup function for this example does the one bit of additional initialization this example needs to do its work, locating the one button in the page and attaching a click event handler to it:

function setup() {
	var greetingButton;

	greetingButton = document.getElementById('greeting');
	greetingButton.addEventListener('click',greetingHandler,false);
}

When Things Go Wrong

An inevitable part of the programming process is making mistakes. Almost no code that programmers write is perfect on the first writing, so catching and fixing mistakes is an essential part of the programming process.

This portion of today's notes will take you through some of the more common mistakes that beginning programmers will make and provide some suggestions on how to catch and fix these errors.

The Console and the Debugger

One of the reasons that I recommend the Chrome browser as the primary browser for this course is the developer tools built into the browser. To access the developer tools, click the ⋮ button at the right end of the address bar and select More Tools/Developer Tools. The developer tools area has a series of tabs across the top. Start by clicking the Console tab.

I am going to artificially introduce an error in the JavaScript code to illustrate what will happen when you make one of the more common errors in programming - forgetting to initialize a variable. I am going to go into the setup function and purposefully comment one of the lines of code, a line that is necessary to properly initialize a DOM variable I need:

function setup() {
	var greetingButton;

	//greetingButton = document.getElementById('greeting');
	greetingButton.addEventListener('click',greetingHandler,false);
}

The setup() function will run on the document load event. As soon as the statement after the statement I commented out runs JavaScript will generate an error. This will cause an error message to appear in the Console window. (You can see that error message in red in the screen shot above.) The error message will reference the line where the error was generated: that line number is a link that you can click. Clicking the link will switch to the source view, where you can view the statement that caused the problem.

The source view is also where we can access one of the more useful develop tools, the debugger. To demonstrate how the debugger works I am going to go back to my editor to remove the comment from the line of code I had previously commented out. After saving the changes and reloading the page in the browser I will go to the source view and click the margin next to line 24 to set a break point.

When you set a break point a blue tab will appear in the margin on that line. The next time the browser's JavaScript system executes that line the system will pause at that point in the code. At that time the source view in the developer tools will look like this:

The line of code where we set the break point is now highlighted to show the line where code execution is paused. In the pane to the right you can also see a list of variables that are active in the current context. You can examine that list of variables to see that all of the variables have values you expect. Finally, the pane to the right contains a set of buttons you can click to control the execution of the code from this point. The first button (in blue) is the run button - clicking this will cause normal code execution to resume. The second button is the step over button - clicking this will cause the system to run one line of code and then pause again.

To remove the break point, simply click on the break point in the margin.

Using the debugger to track down errors

To illustrate another common kind of error, I am going to insert an error in the event handler function for the button. Can you see what the error is?

function greetingHandler() {
	// Declare the variables we will need
	var nameField, resultPar;
	var name, greeting;

	// Gather the page elements we need to interact with
	nameField = document.getElementById('name');
	resultsPar = document.getElementById('result');

	// Get the name the user entered.
	name = nameField.value;

	// Construct a greeting
	greeting = 'Hello, ' + name + '. Welcome to JavaScript!';

	// Present the result
	resultPar.textContent = greeting;
}

Reloading the page and clicking the button generates a error message that you can see the console.

Clicking the link in the error message takes us to the source view, where we can set a break point and try clicking the button again.

When we hit the break point we will get to see the variable display on the right. That display indicates that the variable named resultPar is undefined. This is a clue that we should look back a few lines to the statement that was responsible for setting the value of this variable:

resultsPar = document.getElementById('result');

With our attention drawn to this statement we can see our mistake: I misspelled the name of the resultPar variable in this line. Why did this statement not produce an error message? This error demonstrates one of the peculiar (and frustrating!) aspects of the JavaScript language - it turns out that you don't have to declare variables before using them. Essentially what this incorrect code is doing is introducing a new variable (named resultsPar) and initializing it. This variable gets properly initialized, but the original variable, resultPar, does not.