July 17: Intro to Javascript


Intro

We've now looked at two languages: HTML, which we use to specify the structure of a page, and CSS, which we use to specify the look of the elements in a page. To make a page interactive, we need to go beyond these to something that lets us specify actions to perform and when to perform them. That is, we need a programming language.

A programming language is used to tell a computer how to execute a well-defined set of steps. There are many, many different programming languages out there (a fun illustration of that), with different advantages and disadvantages for instructing computers what to do and how. 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 have a program try to do something "illegal", it could fail in many different (and sometimes difficult to diagnose) ways.

Another important part of a programming language is how we understand what a program means. The semantics defines the meanings of language constructs. For example, we need to understand what the "+" symbol computes (as we'll see, it's not just for addition of numbers). As with human languages, different programming languages can make you think differently.

Javascript (officially JavaScript, though I tend not to write it that way) is a programming language that has grown up hand-in-hand with HTML and CSS and is now one of the technologies underlying many "Web 2.0" applications. The "script" part of the name refers to the notion of scripts as short, high-level programs to control other programs. In our case, we'll be controlling the browser. As the name suggests, by analogy to acting, a script is a list of instructions for the actions that should be taken.

We'll be learning some basic Javascript by way of examples. Even moreso than HTML and CSS, this course will only scratch the surface of the language, but should give you a feel for the types of things one can do with a programming language, and what it's like to think that way. Once you have viewed the HTML source of a file, you can also see the Javascript source (in my version of Firefox, I can click on the .js filename; otherwise, just put that filename in place of the HTML filename in the browser's address bar).

First script

Our first script (be sure to view source and follow through to the Javascript file on this and all examples) uses one of the Javascript capabilities that was widely used early on, but thankfully not so much now. I'll use it briefly because it's simple, and because you might sometimes find it useful in debugging.

script tag
Used to include a script in a web page. Like with CSS we can put the script in a separate file with URL specified as an attribute, or we can include it right there. I'll always use the separate file approach, both because it keeps things nicely separated (structure of document in HTML, style in CSS, and function in JS) and because it allows text editors to properly treat the source (coloring, indenting, etc.).
<script type="text/javascript" src="URL"> </script>
Historically scripts have been placed in the <head>, though they can also go in the <body>, and recently there are some who say it should go at the end of the <body>.
button input
Another input type, for a button whose actions we define (cf. submit).
onclick
An attribute that lets us given a button input it action. The attribute links from the HTML to the Javascript by providing a function to be called when the button is clicked: onclick="greet()".
function definition
A sequence of steps to perform:
function greet() 
{
  /* A sequence of JavaScript statements */
}
The function's name, here greet, is then associated with the sequence of statements. The name should begin with a letter, and can then use letters, numbers, and the underscore (but shouldn't be a name that Javascript reserves for itself). Javascript is case sensitive, so greet and Greet are two different things! The open and close parentheses are required, and later we'll see how to give extra information to a function by listing its parameters there.

Note that the function's body is a sequence of steps, performed top to bottom. Try modifying the example script to do several alerts.

alert
A built-in function to pop up a little window, with a parameter for the message to be displayed.
function call
An execution of the steps defined by a function, called by providing its name, any parameter values enclosed in parentheses, and a semicolon:
alert("Hello!");
parameter
Information needed by a function, like the message to be displayed by alert. Multiple parameters are separated by commas.
string
A piece of text, enclosed in double quotes: "Hello!".
comment
A note to the reader, enclosed in /* and */.
white space
As with HTML, use spacing (particularly indentation and blank lines) to make your code readable. One good rule of thumb is to indent for each curly brace.

Getting input

Next we add a text input to ask for a name, which then gets incorporated into the greeting.

variable
Keeps track of a piece of information. We declare a variable like:
var name = its initial value;
As with functions, the variable name is alphanumeric-with-underscores (starting with a letter, and not conflicting with special Javascript words), and is case sensitive. The initial value isn't required, but is good practice.
document.getElementById
A function to get a Javascript object representing an HTML element. The parameter to the function is a string with the id of the element, which will be matched with the id attribute in the HTML, linking Javascript and HTML together.
object.value
Accesses the value for an input object: name.value gets whatever has been typed into the text box. This is linking back and forth between Javascript (the input object referenced by variable name) and HTML (the actual text input and what's been typed into the browser).
string concatenation
+ sticks two strings together; e.g., "ab"+"cde" produces "abcde".

Acting conditionally

We extend our script to give a different message to a very special person. If the value in the input object is "Chris" we give one message; otherwise we give another.

if/else
To only perform some actions is something is true, we wrap the actions in an if statement:
if ( some test ) {
  /* Javascript statements to do if the test is true */
}
else {
  /* Javascript statements to do if the test is false */
}
The test is something that is either true or false. The else part can be left off if nothing should happen when the test is false.
equality test
A double equal sign, ==, testing whether or not two things have the same value: name.value == "Chris" is either true or false. This is a double equal sign, with the single one used for assignment (as when we give a variable its initial value).

We can further extend this example to make sure that some name was filled in.

else if
Another test to be performed if the first test is false. We can chain as many of these as we like.
empty string
A pair of double quotes, "", indicating a blank value.
inequality test
An exclamation point followed by equal sign, !=, testing whether or not the two things don't have the same value (sorry for the double negative), i.e., the opposite of ==. Thus name.value != "" is true when the name isn't blank.

Debugging

We'll talk more about this later, but I wanted to get a jump start.

  • Firefox has a basic error console (under the tools menu) that points out some errors.
  • As usual, firebug does an even better job, with lots of support for finding errors, seeing how your script is working, etc. (some in-class demos).
  • In a pinch, use alert to print out something to make sure your script got somewhere, has the right value for a variable, etc.
  • JSLink will check your code and give you all kinds of complaints ("Warning: JSLint will hurt your feelings").