Writing Scripts

Now that we know how to trigger scripts, we need to have them doing something interesting. Below you'll find all the basics of JavaScript programming, starting with basic variables and progressing to strings, statements and loops.

Variables

Variables turn up in every programming language since the dawn of time, and you've probably come across the concept somewhere before. You can define a variable as a number or a piece of text, and then use the variable's value in your script. In JavaScript, it is unnecessary to declare the type of the variable (whether it's a number or text), just its name and value. As we shall see, this ambiguity helps us by making it easy to switch between types.

var age = 18;
var introText = "A long, long time ago...";

Think of a variable as a named box that you can put values into. Once we know how to access page objects you will also be able to create variables from the values of form fields etc. Variable names must start with a letter, but can contain numbers. Naming convention states that the first letter is in lowercase, and subsequent words have their first letter capitalised, as in introText.

You can then use these variables like this:

document.write(introText + " I was " + age);

To create the text below. You just drop the variable names into the write parentheses, without the quotes (so the browser doesn't think they're strings), and then join them together with quoted strings with the + sign.

You can define variables without giving them a value (they automatically receive the empty value undefined), by a line like var textLength; — this variable can then be given a value later on.

Arrays

Arrays are special types of variables — each one can hold multiple values. Each of these values has an index, or number in the array, with the first index being 0. For example,

var days = new Array();
days[0] = "Monday";
days[1] = "Tuesday";

And so on. Now, document.write(days[1]) will produce simply Tuesday. Just add the index you want in square brackets after the variable name and you have access to the index's value. An array can have an indefinite number of entries. When you create arrays like this you are actually creating an new array object. This object has properties like its length etc.

Strings

String variables are very important in JavaScript — you use them a lot. They are simply groups of characters, a word, sentence or url for example. They have many properties and methods.

You've seen strings before — the text you placed in the alert was a string. Strings are always delimited by quotes, either single or double. Personally I use single quotes around single characters and double quotes around anything longer. You can do it differently if you want, but be sure you always end a string with the same type of quote that you started it with. Here are two examples:

var a = "Welcome to JavaScript!";
var b = "Enjoy the lessons";

Remember the rule from the previous page — if you put an apostrophe into a single-quoted string, you must escape it with a backslash (\'). It's the same deal with double quotes inside a double-quoted string.

To concatenate, or join two strings, we use a plus sign.

document.write(a + b);

Produces Welcome to JavaScript!Enjoy the lessons. Note that there are no quotes around a and b here, as that would make the letters strings themselves, which is not what we want. We'll want to add a space in there, so modify it to a + ' ' + b. We append in a single-space string to split the other strings up. Of course, we could also add a space to the end of a in place of this new string.

Bringing together words and numbers, while a more problematic process in most languages, is simplified in JavaScript. You can simply write

document.write(a + ' ' + 3 + 2);

In this instance, your browser assumes that everything there is a string, resulting in Welcome to JavaScript! 32. If you want to add the numbers, you can use parentheses to get the addition performed first before the concatenation; like so:

document.write(a + (3 + 2));

Which results in Welcome to JavaScript!5. Other arithmetic operations like subtraction, multiplication or division cause no such problems — you can have a + 3*4 to create Welcome to JavaScript!12.

String Methods

We can find out the length of any string using its length property. a.length produces 22, the number of characters in the string (a space counts as a character). This property is common to all JavaScript strings.

To convert a number into a string, use the toString method.

var c = 8/2 + (9*4) + 1;
var d = c.toString();

You can now use other string methods on d. If you want to use a string variable as a number, just be sure it doesn't have any letters or punctuation in it and then throw it in. If it did have anything other than numbers, your browser will return NaN, which stands for 'Not a Number'.

You can search strings for certain characters using the indexOf method. This finds the index of the specified character (the position it occurs in the string) and returns it. Each character in a string is given a numbered index, starting with 0 as in most programming languages. For instance,

document.write(b.indexOf('y'));

This would return a value of 4, the index corresponding to the first instance of the character 'y' in b. Just remember, the index of the first letter is always zero. You can also search for multiple characters, and you will be presented with the index of the first instance found of any of your characters.

document.write(b.indexOf('o n'));

Finally, it is also possible to find the first instance of a character after a certain index. The following finds the first 's' after the character with index 6.

document.write(b.indexOf('s', 5));

If the method doesn't find the letter within the parameters you have given it, you will receive a value of -1. This comes in handy later on when, using an if statement, you can check if strings contain certain characters at all.

Note that the length (number of characters) of a string is always 1 more than the last index in a string, since the index count starts on 0. This is a very important point to remember.

Some final methods:

string.lastIndexOf('x') gives you the index of the last instance of the character in the string. Otherwise identical to indexOf.

string.charAt(0) gives you the character at the specified index.

string.substring(0, 10) creates a new string from the original, starting at the first number and ending at the second (without including it). If you leave out the second number, the string is printed out to the end.

string.substr(4, 6) is similar to substring, except the second number is how many characters to take, instead of the ending index. This method is not supported by the version 3 browsers.

string.toLowerCase() converts all the characters in the string to lowercase. There is a corresponding method, toUpperCase(), to do the opposite.

A very helpful method is split(), which you can use to split one long string into a group of smaller strings. You specify which character to split at in the parameter parentheses. You need to create a new array to place the string fragments into.

This will split b into pieces at each space. You'll end up with an array like this:

frags[0] = "Enjoy"; frags[1] = "the"; frags[2] = "lessons";

The spaces that went between are gone forever.

Statements

Statements are the basic constructs that make up all scripts. JavaScript has two very important control statements — if() and the for() loop. These elements are common to most programming languages. Before we get onto them, you'll need to know a thing or two about Boolean logic.

Boolean Logic

Boolean logic is used to find out the overall answer to a number of conditional statements. A Boolean value can be either true or false — nothing else. An example statement in common speak would be 'I am tall and the tree is short or cut down'. If this statement turns out to be true, you can steal old Mr. Grimrump's apples.

When programming we're usually comparing values for equality, or seeing which is bigger. For example, x == 1 evaluates to true if x is 1 (note the double equals sign). Otherwise it's false. You also have > (greater than), < (less than), >= (greater than or equal to) and <= (less than or equal to). JavaScript has three evaluation operators:

AND (&&) evaluates to true if all elements are true.

(x == 2 && y <= 18)

OR (||) evaluates to true if at least one of the elements is true.

(x == 4) || (y > 0)

NOT (!=) evaluates to true if the element is false.

(x != 0) && (y != 0) || !(x < 0)

You can declare Boolean variables, like var x = true. Putting an exclamation mark before a variable or equality switches its Boolean value, so then !x will be false. These are the only two values a Boolean variable can take.

sourcetip: The spacing around the Boolean operators isn’t important. x==2 and x == 2 will both be executed the same by your browser, but the latter is much more readable.

if() Statement

The if statement is used to test for equalities. You can execute code only if a specific condition is met. If the statements in the parentheses are true, the code between the curly braces is executed. If it is false, the code is skipped.

You can test multiple evaluations at once, and using parentheses, have certain parts evaluated first (the equalities in parentheses are always evaluated first).

See if you can guess whether the It is true string will be printed. This code is equivalent to 'if y is greater than or equal to 2 AND the opposite of if z is greater than 15; OR if x is NOT 0'. It turns out to be true. If you need it broken down for you I've set up a simple bit of DHTML to guide you through it. Place your mouse on each equality.

You can test for further conditions using else. If your first if statement is not true, your browser will execute the code in the else block.

if (x > 0) {
do something
} else {
do a different something
}

You can also use another if statement in the else, so that it is only executed if the first statement was false and the next is true. You can have a number of elses to cover many possible conditions.

If the first condition is true, the corresponding else statements are not executed, even if they're also true. Also, as you can see from the example above, it's now possible for the entire block of code to be skipped, if x was 1, for example.

It's also possible to compare strings. It's done in exactly the same way — if (a == "Welcome to HTML") {}.

for() Loop

Using a for loop you can execute one block of code a set number of times. For instance, the code below will print 'JavaScript' and a rising number five times:

for (var i=0; i<5; i++) {
document.write("JavaScript" + i);
}

First, a variable i is defined as 0. Then the loop says, for as long as i<5, execute the code block. Each time the loop is run, i is incremented by 1 (i++). After 5 iterations, or runs of the loop, it stops. If you try out this script, you will see the i that gets printed out increasing by 1 each time, starting at 0 and ending at 4 (before it becomes 5).

It is a programming custom to use i for the counter variable. This variable cannot be used outside the loop, to avoid problems. Also, if you find it more logical, you can decrement the variable with i-- until it becomes less than 0, for example.

You can go through all the elements in an array by making the continue condition i<=theArray.length-1. This will go through each index in the array (stopping at the last index, which as you remember is 1 less than the array's length). You can then populate the array with values or perform actions on each index etc.