You are on page 1of 57

Creating a JavaScript program

JavaScript programs are written as a series of program statements embedded in an HTML file (i.e. the instructions for a web page). HTML consists of a series of tags, and one of those tags tells it to start running a JavaScript program. This is the <script> tag as shown below:
<script language="JavaScript"> (The JavaScript program goes here) </script>

The </script> tag at the end of the program tells the web browser interpreting the file that the JavaScript program has finished and it should expect more HTML tags to follow. Whenever the program comes across a <script> tag, then it will assume that the language used is JavaScript, so the language="JavaScript" part of the tag isn't really necessary. The program could just as easily be written as
<script> (The JavaScript program goes here) </script>

However, it is generally a good idea to use the full version of the tag, in order to take account browsers yet to be introduced that may not assume that the default language is JavaScript. The HTML file containing the JavaScript program (together with any other HTML and text, of course) is saved using the file extension .htm, or .html as per normal, of course.

JavaScript is an Object Oriented Language


Everything in JavaScript takes the form of an object. This means that it is a "package", which contains various properties (pieces of information) and methods (lists of instructions that it can carry out). An example of an object in real life might be a bird. The 'properties' of the bird - the information associated with it - are its breed, its plumage colour, details of its diet etc. The 'methods' of the bird would comprise things that it knew how to do, such as sing, fly, peck, breed etc. In Object Oriented computer languages such as JavaScript, the sort of objects would be things like documents (screens), windows, variable types etc. but they still have properties and methods.

The document object Here's the first object that you will meet -

document. This refers to the main screen in the browser itself, the part where the text and images appear. The document has a property (among others) called bgColor, which specifies what the background colour of the screen is (note the capital C in the middle of that. It's important. Also note that 'Color' is spelled the American way). We can use this to set the background colour of the screen. Open your text editor and create a plain text file called test1.htm containing the following text:
<html> <body> <script language="JavaScript"> document.bgColor = "YELLOW"; </script> You can add some more text and/or HTML tags here, of course. </body> </html>

You can add as many HTML tags to that as you like (but don't add a bgcolor= part to the <body> tag, of course, as we are trying to set this using JavaScript). The word document is separated from the bgColor property by a full stop (but don't insert any spaces in there!), and it is used to set the background colour to yellow. When you open the file in a browser, you should see any HTML that you have specified on top of a yellow background.

N.B. The program instruction in the example above ended with a semicolon (;) Program instructions in JavaScript almost always end in a semicolon, so remember to put it in. You should also be careful about letter case. Write the program exactly as you see it here, using document rather than DOCUMENT or Document.

bgColor is an example of a document property. An example of its methods is write() and you can tell that it is a method by the fact that the name of the method is followed by a pair of brackets. write() displays text on the screen. The thing that you want displayed on the screen is enclosed inside the brackets. If it is a piece of text, then remember to place it within double quotation marks:
<script language="JavaScript"> document.bgColor = "YELLOW"; document.write("This should appear on a yellow background."); document.write("<p>"); document.write("This is my second JavaScript program."); </script>

You will see that you can include as many document.write() instructions as you like, and that write() is again separated from the word document with a full stop. Note also the semicolon ; at the end of each program line. The second instruction writes a paragraph break on the screen (i.e. a blank line). The tag <p> in HTML causes a blank line to be inserted and enclosing the HTML tag within a document.write() statement, it has the same effect. In fact, document.write() can duplicate the effect of any HTML tag:
<script language="JavaScript"> document.write("<img src=my_pic.gif>"); document.write("<hr width=40%>"); document.write("<font color=#4050ff>"); </script>

You do still need to enclose the tags within quotation marks. The following would not work at all: document.write(<img src=my_pic.gif>); Another property of document is the lastModified property. This contains the date that the document was last edited - it corresponds to the fileedit date. You can't change this in the same way that you could with the bgColor property, but you can display it on the screen: document.write(document.lastModified); Again, the word lastModified should be written with all lower case letters except for the M in the middle which should be upper case. lastModified is what we call a read-only property - it can be displayed, and its value "read" by

the program (for example, when testing conditions), but it can't be altered by the program. The only way of altering the lastModified property is by editing the file so that the date changes.

Variables A variable represents a piece of data stored in a computer program. All variables have a name and a value. We can think of them as being like small boxes, each of which can contain one item. The name of the variable is how we refer to the box, and the value is the item stored in the box. The diagram shows a variable called x, and the value stored in it is 14.
Variables in JavaScript must be declared before they can be used. They are declared using the word var followed by the variable name and a semicolon: var age; Variable names can consist of any number of upper or lower case letters, digits and underscore characters _ but they must start with a letter. Also, variable names are case sensitive, which means that the variables names myName, MYNAME and Myname would all refer to different variables. Variables are set to values using an equals sign: age = 37; You can also display the values of variables on the screen using document.write(). In this case, put the variable inside the brackets but don't surround it with quotation marks: document.write(age); This will display the number 37. If you had put the word age in quotation marks, as follows, document.write("age");

then the word age would have been displayed on the screen. The value of variables can be changed at any point. Indeed, they can even be set to the value of other variables:
<script language="JavaScript"> var x; var y; x = 26; y = -109; document.write(x); document.write("<p>"); x = 45.7; document.write(x); document.write("<p>"); x = y; document.write(x); document.write("<p>"); </script>

The first number displayed on the screen is 26 (the value of x). The second number displayed is 45.7 (the updated value of x - I didn't say the numbers had to be whole numbers, did I?) and the last number displayed is -109 (after x is set to the same value as y - I didn't say the numbers had to be positive either!) All these numbers are produced by the same instruction - it's just the value of x that changes. Variables can also be set to values at the same time that they are initialised. For instance, the following two instructions
var temporary_value; temporary_value = 26.09;

can be rewritten in one line: var temporary_value = 26.09; You can also declare more than one variable in one line, by separating the variable names with commas (not semicolons - they only come at the end of lines). For instance, the following lines:
var a; var second; var third_variable; a = 7; third_variable = 19; second = 2400;

can be rewritten as
var a, second, third_variable; a = 7;

third_variable = 19; second = 2400;

or even as var a = 7, second = 2400, third_variable = 19;

Arithmetic
As well as setting variables to different values (which isn't particularly useful on its own), we can also perform arithmetic on them. We use + for addition and - for subtraction, * for multiplication and / for division:
var first = 12, second = 4; var sum = first + second; document.write(sum); document.write("<p>"); var difference = first - second; document.write(difference); document.write("<p>"); var product = first * second; document.write(product); document.write("<p>"); var quotient = first / second; document.write(quotient); document.write("<p>");

The value of sum is set to 16 (= 12 + 4), difference is set to 8 (=12 - 4), product is set to 48 (=12 * 4) and quotient is set to 3 (=12 / 4). If the division had not produced a whole number then quotient would have been set to a decimal value (so if second had been set to 5, then quotient is set to 2.4). If you want to, you can put the arithmetic entirely within the document.write() statements, although that would not set any variable values, of course. The following would produce the same four numbers as the program segment that you see above, except that the variables sum, difference etc. are not set:
var first = 12, second document.write(first + document.write("<p>"); document.write(first document.write("<p>"); document.write(first * document.write("<p>"); document.write(first / document.write("<p>"); = 4; second); second); second); second);

You can also mix numbers and variable values in longer arithmetic expressions:
var answer; answer = 14 + sum - product; second = 10 * quotient - answer;

The value of answer is set to 14 + 16 - 48 = -18. The (new) value of second is set to 10 * 3 - (-18) = 30 + 18 = 48.

Operator Precedence
What value is displayed by the following? document.write(2 + 3 * 5); If you said "25", then you would be wrong. Instead of doing the arithmetic operations in the order in which it meets them (2 + 3 = 5, then 5 * 5 = 25), the multiplication is done first and then the add (3 * 5 = 15, 15 + 2 = 17) so the answer 17 is displayed on the screen. The rule is that multiplication and division are more important than addition and subtraction (we say they have a higher precedence) even if they come after the addition or subtraction. Take a look at this: document.write(40 - 5 * temp1 + 100 / temp2); In this case, the value of 5 * temp1 is calculated first, and then the value of 100 / temp2. The program then subtracts the first of these values from 40 and adds the second of the values. If temp1 had the value 7.5 and temp2 had the value 50, then the number displayed would be 40 - 5 * 7.5 + 100 / 50 = 40 37.5 + 2 = 4.5. As in normal mathematics, we can change the order in which the arithmetic is done by enclosing the addition or subtraction within brackets. Brackets mean "do me first", so the following new_answer = (2 + 3) * 5; really would set the value of new_answer to 25. Similarly, the following document.write((x + 2) / (x * 2 - 5));

would calculate x + 2 first, then the value of x * 2 - 5 (doing the multiplication before the subtraction) and then divide the first number by the second, displaying the answer.

String variables
The sort of variables that we have seen up to now are called numeric variables, as they have held nothing but numbers. However, we can also set variables to strings, which are words and sentences. Strings are enclosed within double quotation marks.
var proverb = "Every mushroom cloud has a strontium lining."; document.write(proverb);

This code segment declares a variable and sets it to the string specified. Again, no quotation marks are used in the document.write() statement as otherwise it would display the word "proverb" rather than the value of proverb. Variables can be re-assigned to different strings just as they can be with different numbers: proverb = "A rolling stone gathers much speed."; Indeed, variables can be assigned to a number, then to a string and then back to another number if you want:
proverb = 399; proverb = "Pride comes before private in the dictionary."; proverb = -1000;

That is perfectly acceptable in JavaScript, although it is not a good idea to reassign variables to strings and numbers willy-nilly. Most other programming languages forbid you from doing so, but JavaScript has what we call weak typing, and it is not fussy what values we assign to variables. You can also use the + operator with strings, or variables that have been assigned to strings. Consider the following:
var name = "Richard" + "Bowles"; myVariable = "X@X#X$X"; document.write("This is a string" + myVariable + ".");

The first of those instructions sets the variable name to RichardBowles and the second statement displays This is a stringX@X#X$X. This joining of one string on to the end of another is called concatenation. Note that I had

forgotten to include any spaces in that, so the strings produced had no spaces. If I had wanted spaces, I should have written the statements as follows:
var name = "Richard " + "Bowles"; myVariable = " X@X#X$X "; document.write("This is a string" + myVariable + ".");

Mixing strings with numbers


What happens if + is used to join a number (or numeric variable) to a string (or string variable)? In this case, JavaScript treats both of them as if they were strings and concatenates them accordingly. The following instruction sets temp_var to the string Hello123:
var x = 123; var temp_var = "Hello" + 123;

Similarly, the following instruction displays the string The answer is 1004:
first = 1000; second = 4; answer = first + second; document.write("The answer is " + answer);

However, please be careful. You might think that the following would display the string I have 8 children: document.write("I have " + 5 + 3 + " children"); However, as soon as JavaScript comes across the first +, it realises that we are using string concatenation, and it then uses string concatenation for all the other + operations in the instruction. This means that it displays 5 and 3 as their string equivalents, "5" and "3", which it joins end-to-end to produce the message I have 53 children - not quite the desired answer. If you want the 5 + 3 to be calculated as 8, then you have to insist that JavaScript does it before the other + operations, and this is achieved, as you might expect, using brackets: document.write("I have " + (5 + 3) + " children"); This does have the desired effect, and gives the message I have 8 children. The 5 + 3 is turned into 8, and then JavaScript concatenates "I have " + 8 + " children" as one large string. Here is an example where I have mixed a string with one of the document properties:

document.write("Web page last changed on " + document.lastModified);

JavaScript - Lesson 2

Getting values into the program using prompt(). Turning strings into numbers using parseInt(), parseFloat() and eval(). The alert() function. The % (modulo) operator. Comments

So far we have learned about variables, set them using = to strings and numbers, and displayed the result on the screen using document.write(). However, a program is fairly useless if we have to set all the data in advance, and we need some way of getting the data into the program.

prompt() There is a special instruction called prompt() which displays a box on the screen and asks the user for a value. This is then set into a variable. Here is how you use the instruction:
friend_name = prompt("Please enter your friend's name", "Diane"); What you see is the following:

The prompt box carries a message - in this case, it's Please enter your friend's name and a default value, which is Diane. The idea is that the user types the friend's name instead of this default value, and then click on OK.

If the user didn't type anything, but just clicked on the OK button, then the value stored in the variable would be "Diane". The two items are passed to the prompt() instruction inside the brackets, just as strings to be displayed on the screen are passed to document.write() inside the brackets. We call these parameters. The prompt() instruction takes two parameters: firstly, the message asking for the input, and then the default value. There is a comma between the two parameters. Compare the picture of the box above with the instruction. The space after the comma is optional - I put it in because it tends to make the instruction more readable. Whatever the user types - even if the box is cleared with the delete key and nothing is typed - then that value is stored in the variable. In this case the variable altered is friend_name. If the user typed "Bill Clinton" in the box, then the instruction would be equivalent to the instruction friend_name = "Bill Clinton"; If the user cleared the box (i.e. deleted the default value using the Del key) and then clicked on OK, then the instruction is equivalent to typing: friend_name = ""; (i.e. an empty string). What is the value to which the variable is set if the user clicks on Cancel? That I will leave you to find out for yourself! If you don't want to specify a default value (i.e. you want the slot to be blank when the box appears) then just specify the default value as a blank string, as follows: var proverb = prompt("Type a saying", "");

In this case, there is no default value. Similarly, you could leave the prompt message blank as well, although the user would probably not know what he or she was required to enter!

Converting strings to numbers


The problem with the prompt() instruction is it always returns a string. If we used it to get two numbers from the user and add them, we are going to run into problems:
<script language="JavaScript"> var first_number = prompt("Enter the first number", ""); var second_number = prompt("Enter the second number", ""); var answer = first_number + second_number; document.write("The answer is " + answer); </script>

If you enter 3 for the first number and 5.6 for the second, you should get the answer 8.6, but in fact you get the answer 35.6. What's gone wrong? Well, the variables first_number and second_number are set to the string values "3" and "5.6" which, although they look like numbers are actually strings. The + sign then concatenates them to form a longer string. What we want is a way to convert the string that prompt() gives us into a number. There are two instructions that we can use, parseInt() and parseFloat(). The instruction parseInt() will take a string, either as a constant inside quotation marks or a variable, or even as an expression, and will turn it into a whole number. The 'whole' is important in that - the "Int" part of the instruction stands for "integer", which is the technical name for a whole number. For instance, the following instruction stores the number 7 in the variable x: x = parseInt("7"); Similarly, the following instruction adds the number 4.55 to the number 10 and displays the result (14.55) on the screen:
var digit0 = "0"; document.write(4.55 + parseInt("1" + digit0) + "<p>");

The first thing that happens in that instruction is that the two strings "1" and "0" (stored in the variable digit0) are concatenated into the string "10". The instruction parseInt() then turns this into the number 10, which is then added to the number 4.55. The number is then concatenated with the "<p>" tag (giving a paragraph break) and the whole lot is displayed on the screen. "Ah!" I hear you say, "I thought that concatenating numbers with strings would turn the numbers into strings themselves. You should get 4.5510 on the string, shouldn't you?" No. The command we have above is equivalent to document.write(4.55 + 10 + "<p>"); In this case, the first + sign that the instruction comes across is the numeric addition - it adds the numbers together. It is only after this that it encounters + with a string following it. At this point, it takes the answer to the addition and concatenates it with the string containing <p>. So what is parseFloat() then? Well, this is the instruction you would use if you thought that the answer might be a decimal (non whole number) answer. For instance, if you asked the user for the length of a building or the weight of an elephant, then these could well be decimals:
var elephant, building; var string1, string2; string1 = prompt("Enter the length of the building in yards", ""); building = parseFloat(string1); string2 = prompt("Enter the weight of the elephant in tons", ""); elephant = parseFloat(string2);

Of course, if parseFloat() is handed a whole number, it can still cope with it. It doesn't have to produce a decimal number. Indeed decimals can be whole numbers themselves (i.e. there is nothing special about 7, as it is the same as 7.0). The following instruction is perfectly correct:
var x = "500"; var y = parseFloat(x); document.write(y + 100);

It will set the variable y to the number 500. This is proved by the document.write() instruction which correctly adds the variable to 100 and displays the number 600. The word 'Float' stands for "floating point number" which is the technical name for a decimal number. That example has also shown how we can solve our

problem with the addition program you saw above. Change the program to the following, and it should work properly:
<script language="JavaScript"> var first_number = parseFloat(prompt("Enter the first number", "")); var second_number = parseFloat(prompt("Enter the second number", "")); var answer = first_number + second_number; document.write("The answer is " + answer); </script>

Here we have included one instruction inside another. The prompt() instruction produces a string, and instead of storing this string in a variable, it is handed straight to the parseFloat() instruction which turns it into a decimal number. The string entered is never actually stored anyway, only the floating point number.

The eval() instruction


There is another, slightly more powerful, way to evaluate strings, namely the eval() function. This works in almost the same way as parseFloat(), so it can produce decimal numbers as well as whole numbers. However, it can also evaluate simple mathematics in strings. Take a look at this:
var x = eval("2 * 2"); document.write(x);

In this case, the string contains the expression 2*2 (It also contains spaces, but these are ignored when any mathematics is carried out). The instruction eval("2 * 2") works out the answer to this calculation and that becomes the value of x. The document.write(x) instruction displays the number 4 on the screen. You can also include variables inside the mathematical expression and they will be evaluated correctly. For instance, if you changed the example above to be:
var temp_val = 100; var p = 4.5; var x = eval("temp_val - 3 * p"); document.write(x);

In this case, the expression is equivalent to 100 - 3 * 4.5 and the value displayed is 86.5.

The alert() instruction

There is an alternative way to display messages. variables, numbers etc. on the screen which grabs your attention slightly more than document.write() does. This is the alert() instruction. It is called in a similar manner to document.write(), i.e. the item to be displayed are enclosed within brackets: alert("The answer is " + answer); This produces a grey box on the screen and a bleep noise. The box won't disappear or let you carry on with the program until you click on the OK button. You will notice that you don't need to preface the word alert with the word document or a full stop. This is because the alert() instruction is not a method belonging to the document object (Instead, it belongs to the window object, but that's another story ...)

The modulo operator


There is one mathematical operator that you haven't met yet. It is called modulo and is written as %. It gives the remainder when a division is carried out. For instance, the following program displays the number 2 on the screen, as 17 divided by 3 gives the answer 5 with a remainder of 2.
<script language="JavaScript"> document.write(17 % 3)[ </script>

Modulo can be used with variables, expressions etc. - in fact anywhere that ordinary division is used. Please note that ordinary division will not simply produce the whole number part of the division, it will produce a decimal, so the first line of the following program will produce 4.347826 as the answer (in an alert box, of course), and the second line will produce 8 (the remainder when 100 is divided by 23).
<script language="JavaScript"> var first = 100, second = 23; alert(first / second);

alert(first % second); </script>

Comments
Often you will need to include small messages inside your program which are not intended to be displayed on the screen, nor instructions to the computer, but just to remind you at a later date about how the program works. This is especially true if the program is long and complex, or if you want some other programmer to look at your code - you have to inform that person about any quirks of your program. Such reminders are called comments. The most common way of inserting a comment into a program is by using two forward slashes, //, together (no spaces between them). Anything following that on the same line is ignored until the end of the line is reached. Then the browser starts taking notice again. Here is an example of a comment:
var x = 23; // tax rate tax = turnover * x / 100; // Calculate tax paid net_profit = turnover - tax;

The words 'tax paid' and 'Calculate tax paid' are ignored by the program. They are messages to any human looking at the JavaScript code. Please note, that if you put any instructions after // then they will also be ignored:
var x = 23; // tax rate tax = turnover * x / 100; // Calculate tax paid net_profit = turnover - tax;

In this case, the instruction that calculates the tax is ignored - the program assumes it is part of the comment. This example also shows that you can have a comment at the start of the line (i.e. the entire line is dedicated to the comment), or you can have a comment on a line which contains nothing else but spaces:
var rows = 30; // This line defines the number of rows // of pixels in the image.

There is a second way to put comments in a program, using the symbol /* to start the comment and the symbol */ to end it. The example above could be rewritten as follows:
var rows = 30; /* This line defines the number of rows of pixels in the image. */

You will now notice two things:

We don't need a special symbol at the start of the second line to indicate that it contains a comment. The comment "carries on" from the previous line. Comments can now extend over as many lines as you like. Indeed, if you forget to include the */ at the end of the comment, the browser would treat the whole of the rest of the program as a comment! (I have "lost" massive sections of code in that way!)

We can also, if we want, put program statements after comments on a line, if we want to. The following statement would also work (although I wouldn't recommend writing code like this!):
x = /* Hello! */ 23;

The browser ignores the comment, but recognises the x = before it and the 23 afterwards. It is equivalent to the statement
x = 23;

JavaScript - Lesson 3. Decisions, decisions!


The if statement Comparators AND && and OR || Operator Precedence else switch

The if statement
This is the simplest way in which we can get a JavaScript program to make decisions. In its simplest form, the if statement looks like this:
if (condition) { // Statements to be executed go here // Put in as many statements as you think fit }

The condition is a statement which may be true or may be false. If it is true, the statements inside the { } are executed. If the conditions is false, the statements aren't executed. Here's an example:
var userInput = prompt("Please enter a number",""); var actualNumber = parseFloat(userInput); // Remember, the previous statement turns the string into a number if (actualNumber > 100) { document.write("You entered a really big number!"); }

This short program gets the user to enter a number. If the number is bigger than 100 (actualNumber > 100), then the message is written on the screen. If the number isn't bigger than 100, then no message appears. In fact, if the curly brackets after the condition only contain one statement, as they do in the example above (just the document.write statement), then you don't really need the curly brackets. I could have missed them out, and it would have had no effect on the program:
var userInput = prompt("Please enter a number",""); var actualNumber = parseFloat(userInput); // Remember, the previous statement turns the string into a number if (actualNumber > 100) document.write("You entered a really big number!");

I have indented the document.write statement to indicate that it is controlled by the if statement, but this isn't really necessary. Remember, JavaScript is quite tolerant of the way that you lay out your statements on the screen, so both the statement could just as easily have been laid out as follows:
if (actualNumber > 100) document.write("You entered a really big number!"); if (actualNumber > 100) document.write("You entered a really big number!");

It is useful to indent statements controlled by an if statement, as it gives a clear indication of the fact that they may be executed or they may not depending on whether the condition succeeds or not - and it is a good habit to get into. Of course, you don't have to write messages on the screen:
if (a + b < 250) { var1 = a * b; var2 = "Too small"; }

If the sum of a and b is less than 250, then two variables are set. The variable var1 is set to a*b (whatever value that is) and var2 is set to the string "Too small". If the condition fails, then these variables aren't set. You will notice that there is no need for an if statement to display anything on the screen using alert() or document.write(). Although I tend to include these a lot in my if statements, it is merely to demonstrate to the user whether the condition has succeeded or not. You will see that I have put the curly brackets back in in that last example. This is because the if statement controlled two statements, not one, and the curly brackets were necessary to "glue them together". Please note also: there is no semicolon at the end of the first line. Here I have duplicated the example and put in a semicolon:
if (a + b < 250); { var1 = a * b; var2 = "Too small"; }

This is wrong, and the browser would complain bitterly!

Comparators
Symbols such as < and > are called comparators, because they compare two items. There are six of these altogether:

> bigger than >= bigger than/equal to == equal to < less than <= less than/equal to != not equal to
Please note, if you want to test whether two things are equal to each other, use a double equals sign (==) rather than a single one (=). If you want to test whether two things are different (not equal), then put a ! sign in front of the equals (! =).
var userInput = prompt("Please enter any number except 6",""); var num = parseFloat(userInput); if (num == 6) document.write("No, idiot! You entered 6.");

One of the most common errors (it has caught me many times) is putting a single equals sign in tests rather than double ones. JavaScript should spot these and point them out to you! The following, for example, is wrong:
if (num = 6) document.write("No, idiot! You entered 6.");

AND && and OR ||


You can join conditions together to form multiple ones. If you include the symbol && between two conditions, then the if statement only passes if both the individual conditions are true. For example:
if (a < 10 && a > 0) { // These statements are only executed if a is less than 10 and a // is bigger than 0 i.e. if a is between 0 and 10. } if (friend1 == "Tony" && friend2 == "Jim" && friend3 == "Pete") { // These statements are only run if all the variables match // the values specified }

If any one of the conditions joined by && fails, then the whole of the joint condition fails. Similarly, you can join the conditions with || which means that the condition will succeed if either one (or both) of the conditions passes. This is less fussy than && - as long as at least one of the conditions succeeds, then the entire condition will succeed:
if (val == 1 || val == 2.6 || val > 10) alert("You entered 1, 2.6 or any number bigger than 10");

Operator Precedence
Consider this line which has been extracted from an if statement: if (a > 6 || b < 10 && c == 4) Here we have three comparisons joined together, the first two with || (OR) and the second two with && (AND). The question is: When the browser works out the conditions, does it do the || first, or the && first? The rule is, JavaScript always does the && first (unless there are brackets more on this later!) This means that the browser works out b < 10 && c

== 4 first. If b is less than 10 and c is 4, then this part of the condition is true. It then matches the result of this test with a > 6 using ||, i.e. if either a is larger than 6, or the result of the previous && part was true, then the whole test passes. If this all seems rather complex, I have summarised the action of the if statement above in a table, showing whether each of the individual parts is/are true, the result of the entire if statement (i.e. does the entire condition inside the brackets succeed or fail?) and a comment where appropriate:

a > 6? No No No No Yes Yes Yes Yes

b < 10? No No Yes Yes No No Yes Yes

c == Does the whole thing Comment 4? succeed? No No Yes No No No Yes Yes No Yes In these cases, the states of b and c Yes Yes don't matter, as No Yes a > 6 and that is enough to make the Yes Yes || part work!

Although JavaScript normally does the && part first, you can make the || more important than the && part by putting it within brackets. The brackets should include the || itself, and the conditions on either side of it, as shown in the following example: if ((a > 6 || b < 10) && c == 4) You will notice that we now have a pair of round brackets within another pair of round brackets. This looks odd, but is grammatically correct. In this case, the (a > 6 || b < 10) part is worked out false, and then the result is

matched with c == 4 using &&. Just look what difference it makes to the table of results:

a > 6? No No No No Yes Yes Yes Yes else

b < 10? No No Yes Yes No No Yes Yes

c == 4? No Yes No Yes No Yes No Yes

Does the whole thing succeed? No No No Yes No Yes No Yes

What you saw up above was the simple version of the if statement. You can also add an else clause as follows:
if (condition) { // Statements which are executed if the condition passes } else { // Statements which are executed if the condition fails }

The statements which follow the else are only executed if the condition fails. In this way, at least one set of statements is carried out - either before the else or after it. Of course, there is no reason why you can't put one if statement inside another:
if (a == 6) document.write("The value of a is 6"); else if (b > 10) document.write("b is larger than 10 and a is not 6");

In this case, two closing curly brackets, }, at the end of the statement. By tracing these brackets upwards, you should be able to see which opening curly

brackets, {, they match. Needless to say, aligning the brackets carefully, as you see in the example above, is useful to ensure that all the brackets are matched correctly. Below I have written the same example again, but this time the second if statement also has an else part:
if (a == 6) document.write("The value of a is 6"); else { if (b > 10) document.write("b is larger than 10 and a is not 6"); else document.write("b is 10 or less, and a is not 6"); }

The switch statement The command switch is a variation on the if statement. Instead of having a condition which can be true and false (i.e. the decision can go one of two ways), the value of a variable is tested. The switch statement can then do one of several different things, depending on what the value of the variable is. Here is an example of a switch statement:
switch (myVariable) { case 1 : a = 6; b += 2; document.write("I have altered a and b"); break; case 4.6: p = a + 10; alert("Not a valid option"); break; case -20: b = a - 2 * p; break; default: alert("Unexpected value encountered."); }

In this case, the program tests the value of the variable myVariable. If myVariable has the value 1, then the block of statements after case 1: is carried out. When the program reaches the word break at the end of the block, it skips all the other cases and carries on after the switch statement.

Similarly, if myVariable has the value 4.6, then the block of statements after case 4.6: is carried out. Again, when the program reaches the work break, it jumps to the end of the switch statement (the curly bracket at the end) and carries on with the rest of the program. The switch statement also specifies an action to be carried out if myVariable has the value -20. The default part of the switch statement - which is optional - tells the program what to do if myVariable doesnt have any of the values specified. For instance, if myVariable had the value 6 or -100, then the default part of the switch statement would be executed. You will notice that the default part doesnt have a break after it. This is because, if the switch statement has a default part, then it is always the last item in the statement, so it doesnt need a break to jump to the end. Please note the following about switch statements:

You can only test the value of a simple variable, not an expression. For that reason, a switch statement that started like this:
switch (a) { case 25 : // etc.

would be perfectly legal, but one that started off as follows:


switch (a + b) { case -40 : // etc.

would not be. This is because a + b is not a simple variable.

Unlike if statements, where the statements need to be blocked together using opening and closing curly brackets, { and }, the statements that form the parts of the switch statement dont need to be. The starting point for each block of statements is obvious - it is the word case followed by the appropriate value - and the stopping point of the block is equally obvious - it is the word break that instructs the program to skip over the rest of the switch statement. Note which parts of the switch statement require a semicolon and which do not. Like the if statement, there is no semicolon after the variable being tested. The statements making up the cases have semicolons at the end as usual.

In fact, the word break is optional at the end of each block. However, if you dont include it, the program will not skip to the end when it reaches that point. Instead it will carry on with the statements for the next case! This may be what you want, of course, but please check to see whether you need to include break or not.

Here is another example of a switch statement. It comes from a program to check the amount of income tax a person is supposed to pay. People fall into one of three tax bands, and the tax is calculated from their income in one of three different ways:
switch (taxBand) { case 1 : tax_due = (income - taxAllowance) / 5; break; case 2 : if (income > 20000) tax_due = (income - taxAllowance - 20000) * 0.13; else tax_due = (income - taxAllowance) * 0.13; break; case 3 : tax_due = income * 0.11; }

You will notice that there is no default part to this switch statement (I did say it was optional!). That is fine, as long as you are sure that the variable taxBand will have one of the specified values. If it doesn't then the switch statement will do nothing, and execution will carry on with the statement after the switch. Since nothing comes after the case where the taxBand is 3, there is no need for a break at the end of this statement either.

JavaScript Lesson 4 - Loops


The ++ notation The while loop The do-while loop The for loop Nested loops

A loop is computer instruction which allows a program to repeat a sequence of statements more than once. There is a special computer term for this - we call it iteration. There are three types of loop in JavaScript, and each has its own specific uses: the while loop, the do-while loop and the for loop.

Each loop has a starting point in the program and an ending point, and includes either one statement or a whole block of statements. As you met before with the if statement, blocks of statements are enclosed within curly brackets, { like this }.

The ++ notation
Before we start talking about loops, I must mention a special notation that you will meet a lot in this section. You may see variables with ++ directly after them (with no intervening spaces). This simply means "increase the value of this variable by 1". Here is an example:
x = 2; alert(x); x++; alert(x); // This displays 2 on the screen // Increase x by 1 // This displays 3 on the screen

The command x++ increased the value of x, in this case, from 2 to 3. You will notice that I did not use the keyword var in front of variable x when I first referred to it. This is because the statements that you see above have been taken from a larger program, and I am assuming that the variable x is declared properly previously using the var statement. Remember, with any variable, you only declare it using var once - after that you just use it without var. This process of increasing a number by 1 can be done with any variable that holds a number (i.e. a whole number or a decimal number, positive, negative or zero), but it could not be done with a variable that contained a string. The following, for instance, would produce an error:
x = "I am a string"; x++; // This should cause an error!

It is meaningless to "increase the value of a string by 1". There is a similar instruction called -- which decreases the value of a variable by 1 when it is placed directly after a variable name:
var long_variable_name = 20; long_variable_name--; y = long_variable_name + 10;

Here I have not put in any alert() statements, so that section of code would not produce any output on the screen. The variable long_variable_name starts off as 20, but is immediately reduced to 19 by the -- command. The value of the variable y is then set to 19 + 10, i.e. 29.

We can adapt the instruction so that it adds on or subtracts numbers other than 1. This is done by putting a plus (or minus) sign just before the equals sign in assignment:
first += 10; second -= 23.4;

The first instruction here adds on 10 to the value of first, so that its value increases by 10. Similarly, the second instruction decreases the value of second by 23.4. Please note that there is no space between the + or - sign and the = sign. Note also the difference between the statements that you see above and the following code, which is almost identical.
first = 10; second = 23.4;

Missing out the + or - sign directly before the = sign causes the variables to be set to those values, not increased or decreased by those values. You can also multiply or divide a variable in a similar way by putting a * or / sign directly before the = sign. For example:
var temp_value = 1000; temp_value /= 10; alert(temp_value); // This displays the value 100; temp_value *= 4; alert(temp_value); // This displays the value 400;

You can also use the instruction %= to set a variable to the remainder when that same variable is divided by the following number. Perhaps an example will make that clearer:
var x = 79; x %= 5;

In this case, when x is divided by 5, the remainder is 4, so x is set to the value 4.

The while loop


This loop specifies a condition at the start, and continues to iterate all the time that the condition remains true. The condition can be as complicated as you like, involving the use of && and || just as with if - else statements. The format of the while loop is as follows:

while (condition) { // Statements forming the body of the loop go here }

Take a look at this example:


<SCRIPT LANGUAGE="JavaScript"> var x = 2; while (x < 1000) { document.write(x + "<BR>"); x *= 2; } document.write("The loop has terminated!"); </SCRIPT>

The variable x is initialised to 2. When the loop is first encountered, the condition (Is x less than 1000?) is evaluated. It succeeds, so the loop is executed. The value of x is displayed, and then x is multiplied by 2. Then the condition is tried again, with x now equal to 4. This is still less than 1000, so the loop is executed again. In fact, the loop carries on executing until the value of x is set to 1024. The condition then tests to see whether it is less than 1000 - it isn't, so the loop is not executed, and the program continues with the statement after the end of the loop, i.e. the program displays the message "The loop has terminated". What you see on the screen is the following:
2 4 8 16 32 64 128 256 512 The loop has terminated!

Please note that the value of 1024 is not displayed on the screen. The reason is that the multiply statement sets the value of x to 1024 at the end of the loop, and the very next thing that happens is that x is tested to see if it is still less than 1000. Since the test fails, the document.write(x + "<BR>") statement is never executed again.

It is perfectly possible for the loop never to execute at all. For instance, if the second line of the program above were changed to var x = 1500; Then no numbers are displayed on the screen. When the condition is tested for the first time, it fails (x is not less than 1000) and so the loop is never executed. The message about the loop having terminated is still displayed, of course, because that does not form part of the body of the loop.

The do-while loop


This loop is similar to the while loop, but with one subtle difference. This time, the condition is tested at the end of each iteration of the loop. This means that the loop must iterate at least once. It can never be skipped entirely. The format of the do-while loop is as follows:
do { // Statements forming the body of the loop go here } while (condition);

Note that there is a semicolon after the bracket in the last line. In the following example, the user is asked to enter a number in the range 1 to 10, and the program won't accept any number which is out of this range:
do { var s = prompt("Please enter a number (1 to 10) : ",""); num = parseInt(s); } while (num < 1 || num > 10);

In this case the condition is that the number is out of range (less than 1 or greater than 10) as we want the loop to repeat and repeat until the number is in range. As soon as the user enters a suitable number, we want the loop to terminate. In the case of the do-while loop, the curly brackets are necessary to enclose the statements. With the other sorts of loops, you can miss out the curly brackets if you only have one statement to include (just as you can with if statements), but with the do-while loop, they are necessary. The following:
do x += 2; while (x < 2500);

Would be illegal. It would have to be written as


do { x += 2; } while (x < 2500);

for loops
These are the hardest types of loop to learn, but probably the most powerful. They are normally used when you want a variable to count upwards or downwards, but they don't have to be by any means. The for loop contains a header enclosed within brackets. There are three parts to the header, separated by semicolons:
for (initialisation; continuing condition; end-of-loop statement) { // Statements making up the loop go here }

The initialisation part is a statement which is carried out before the loop is executed. It normally sets a variable to a certain starting value. The continuing condition is a condition tested at the start of each iteration. If the condition is true, then the loop iterates - and carries on repeating until the condition fails. The end-of-loop statement is an instruction that is carried out at the end of each iteration. This normally takes the form of the variable set up in the initialisation statement being increased or decreased. Typically a for loop might look like this:
for (count = 0; count < 20; count++) document.write("The value of count is " + count + "<BR>"); document.write("After the loop, count is " + count);

This loop starts by setting the variable count to 0. The test is carried out: Is count less than 20? Yes it is, so the loop is executed. The document.write() statement is executed ("The value of count is 0"). The end-of-loop statement is carried out (count++) and the value of count goes up to 1. The whole thing is repeated, and the new value 1 is displayed. In fact, the values 0 to 19 are displayed on separate lines. Notice that the value 20 is not displayed, because as soon as count is set to 20, the continuing condition fails (count is no longer less than 20) and so the loop is not executed.

One other point to notice here: There is only one document.write() statement inside the loop. This is because the there are no curly brackets in the loop. When a for loop contains no curly brackets, then the program assumes it only contains the single statement after the for header. The other document.write() statement in the example above is only executed after the loop has finished - it displays the final value of count, which, you won't be surprised to learn, has reached 20. Here is another loop with slightly more complex arithmetic:
var x, sum = 0, a = 100; for (x = 20.5; 2 * x + 1 < 100 + x; a /= 2) { sum += x; x += a / 2; } alert("Sum is " + sum);

Want to see this demonstrated?

This loop is complicated, and I don't think anyone would write it quite like that, but it does illustrate a point. When the loop starts, x is set to 20.5. Before each iteration takes place, the condition is tested to see if twice x plus 1 is (still) less than 100 more than x. If it is, then the main body of the loop is carried out. You can probably see that the condition could be rewritten as (x < 99) with exactly the same results, but I am trying to demonstrate that conditions can be fairly complex here! In this case the end-of-loop statement doesn't work on x directly, which is unusual. Instead, it works on a variable called a, and in the main body of the loop, the value of a is used to alter the value of x. This means that the continuing condition does eventually fail, and the statement after the end of the loop (the alert() statement) is executed. If you work through the loop on paper (or indeed run it as a program) you will find that it displays the value 186.5. In this case, the curly brackets were necessary as there were two statements within the main body of the loop. It is quite easy to write a for loop that never ends, either accidentally or on purpose, as is the case with while or dowhile loops. For instance, if one of the statements were removed from that example:
var x, sum = 0, a = 100; for (x = 20.5; 2 * x + 1 < 100 + x; a /= 2) { sum += x; } alert("Sum is " + sum);

(I have kept the curly brackets in, even though they are now no longer really necessary). In this case, although the value of a is changed at the end of each iteration of the loop, the value of x is never changed, and the terminating condition never fails. This loop would continue for ever - so beware!

Nested loops
It is perfectly possible to include one loop entirely within another. Such loops are known as nested loops. Here is an example, which displays all the times tables, from 1 x 1 = 1 to 12 x 12 = 144 on the screen:
var table, index; for (table = 1; table <= 12; table++) { document.write("<P>"); // Blank line between tables for (index = 1; index <= 12; index++) document.write(index + " x " + table + " = " + (index*table) + "<BR>"); }

This example shows a for loop nested within another for loop. Of course, there is no reason why the two different loops should be of the same variety. Here is the same example rewritten so that a for loop is nested inside a while loop:
var table = 1, index; while (table <= 12) { document.write("<P>"); // Blank line between tables for (index = 1; index <= 12; index++) document.write(index + " x " + table + " = " + (index * table) + "<BR>"); table++; }

JavaScript - Lesson 5, Arrays

Lesson objectives

One, two and multi-dimensional arrays Assigning arrays - a warning Array properties and methods: o length o sort() o reverse()

The best way to think of an array is as a series of pigeon-holes. Each pigeonhole, or element of the array, can hold one value - string or number - just as an ordinary variable can. The array has a name, just like an ordinary variable, and

you get access to the elements using a different positive number for each one (0 for the first one, 1 for the second, 2 for the third etc.) The numbers used are called the indices of the array. Here's an example - a one-dimensional array which I shall call myArray (for want of a better name):

The array is declared as follows: var myArray = new Array(); The individual elements are set up as follows:
myArray[0] = 41; myArray[1] = -5; myArray[2] = 20;

// etc. The others are set up similarly

You'll notice that the array, unlike a simple variable, has to be declared using the word new followed by the word Array and then a pair of parentheses. There is no way of getting round this. However, there is an alternative way to set the values in the array elements. Just as ordinary variables can be set to values at the same time as they are declared, you can do the same with arrays: var myArray = new Array(41, -5, 20, 0, 3, -11, 37); The elements must be enclosed within square brackets [] rather than round ones (). The elements of the array can be used anywhere where a normal number can be used. For instance, all the following are perfectly legal:
alert("The value is " + myArray[4]); x = 2 * myArray[i] + myArray[3 * count - 6]; myArray[j] = myArray[j-1] + myArray[j+1];

From this you will see that:

The indices of the array can be variables (such as i or j in the examples above) or even expressions (such as 3 * count - 6 in the example above). The expressions can include spaces - I tend to put them in to make the expressions more readable.

You can change the values stored in the array at any point. Just as other variables can change their values (that's why they're called variables!) so can array values.

You can use any array value that has been already set up. Here, for instance, is another array:
var another = new Array(); another[3] = -45.6; another[5] = "Richard";

This example shows you that arrays can hold numbers in some elements and strings in others! In this case
alert(another[3]); alert(another[5]);

will produce the values that you expect. However, the instruction alert(another[4]); will produce the special value NaN, which isn't really a number or a string, but stands for "Not A Number". This is because another[4] hasn't been assigned to a string or numeric value yet. Arrays are often used with for loops and other loops. Here is a for loop that displays the contents of an array on the screen with a paragraph break between each element:
for (x = 0; x < 10; x++) { document.write(values[x]); if (x < 9) document.write("<P>"); }

The if statement is in there to ensure that there is no paragraph break after the last element of the array has been displayed. Here is another loop that adds together all the elements of an array - but ignores all the ones that aren't divisible by 5:
var sum = 0; // The sum starts off at 0 count = 0; do { if (listOfNumbers[count] % 5 == 0) sum += listOfNumbers[count]; // Add the value to the sum count++; }

while (count < 83);

That could probably have been written more succinctly using a for loop, but I like to ring the changes. Just because array elements start at 0 doesn't mean that you have to use every element. You may come across a problem where you need array elements from 100 to 120 only. In that case, simply ignore the elements that you don't need!

Two- and multi-dimensional arrays


The arrays that we have been looking at so far are one-dimensional arrays - the values stretch out in a line. We can also declare and use two-dimensional arrays:

In this case, since we have rows and columns, we need two numbers to specify an elements of the array. If we have declared an array called twoDimGrid, then it could be accessed as follows:
twoDimGrid[0][0] = 34; twoDimGrid[2][4] = 30; twoDimGrid[1][5] = 20;

// etc.

Declaring and using two dimensional arrays is done in a similar way to onedimensional arrays, except that each column of the array must be declared individually:
var twoDimGrid = new Array(); // This declares the array itself twoDimGrid[0] = new Array(); // This declares the first column twoDimGrid[0][3] = 31; // Now we can use the elements in the first row twoDimGrid[0][6] = twoDimGrid[0][3] - 32; twoDimGrid[2] = new Array(); // This declares the third column twoDimGrid[2][6] = 26; // Now we can use the elements in the third column

Each column must be declared using the new Array() instruction separately, but they needn't be declared in order, and you can easily miss some of them out if you don't need those elements (e.g. we didn't declare the second column in the example above). You will also notice that the only var command is needed for the initial declaration - you don't need one when you declare each column. Probably the easiest way to declare all those columns is to use a loop:
var square = new Array(); var count; for (count = 0; count < 7; count++) square[count] = new Array(); // This declares each column in turn

The first iteration of the loop declares square[0] as an array, the second iteration declares square[1] as an array, the third iteration declares square[2] as an array etc. At the end of the loop, the array has 7 columns (numbered from 0 to 6 etc.), although there is nothing to stop you adding more later. Then you can manipulate the elements to your heart's content. Similarly, there is nothing to stop us using a declaring arrays with as many dimensions as we like (subject only to memory requirements). The following example shows a three-dimensional array:

This is set up in a similar way:


var cube = new Array(); cube[0] = new Array(); // This gives us a two dimensional array cube[0][0] = new Array(); // This gives us a three dimensional array cube[0][0][3] = "Hello"; // This is how we use a three dimensional array

Of course, we would have to go through a lot more commands to get all the rows and columns set up.

Assigning arrays - a warning


Here we have a small program which declares two arrays - one called first, the other called second. The elements of first are set up so that they hold the numbers 1, 2, 3, etc. and then, the program copies every element of first into second. With me so far? Right ...
var first = new Array(); for (count = 0; count < 100; count++) first[count] = count; var second = new Array() for (count = 0; count < 100; count++) // Copying! second[count] = first[count]; // Copying!

In this case, first[50] holds the value 50, and second[50] holds the value 50 as well, as you might expect. The following instruction alters the vale of first[50]:
first[50] = 345.112; document.write("The value of first[50] is " + first[50] + "<BR>"); document.write("The value of second[50] is " + second[50] + "<BR>");

The instructions display:


The value of first[50] is 345.112 The value of second[50] is 50

However, suppose we had altered the part of the program where the elements are copied from first to second (the lines marked Copying! In the program above) to this: second = first; This will also make the elements of second be the same as first. However, rerunning the program produces the following output:
The value of first[50] is 345.112; The value of second[50] is 345.112;

Although we have only altered the value of first[50], the value of second[50] has changed also. What has happened? Well, in fact, the statement second = first has made both the variables second and first point to the same set of numbers. Instead of being two separate variables, there is only one copy of the numbers with two variables pointing to it. If you want two separate copies of the numbers, use the first method of copying the elements. If you want two ways of accessing the same elements, use the second way.

Array properties and methods


As you can see, arrays are not like your average variables! In fact, they are objects. You will remember from the first lesson that pretty much everything in JavaScript is an object - with properties (pieces of information associated with them) and methods (small groups of instructions) associated with them. Arrays also have properties and methods.
length The length property gives 1 more than the highest index of a declared value in the array. This means that if you declared an array called stockName and set up values as follows:
var stockName = new Array(); stockName[4] = "Fluffy Soap"; stockName[7] = "Wizzo Flakes"; document.write(stockName.length);

The value displayed on the screen is 8, because the highest defined index is 7, even though only two of those elements are defined. When there are no gaps in the elements defined, the length property gives you the number of elements in the array (remember, the first element is 0, so the number of elements would be one more than the highest index) - which is why it is called the length. This can be useful if you can't remember how many elements there are in the array, or the number of elements is liable to change. For instance, to add the elements of the array, the code would be:
sum = 0; for (x = 0; x < myArray.length; x++) sum += myArray[x];

In this case, we don't need to know the length of the array in advance, the length property will fill that number in automatically.
sort()

This is a method built into arrays which sorts them into ascending order. The command is used as follows: myArray.sort(); There is no need for special assignment here. However, be warned! The array assumes that the elements of the array are strings, even if you have filled it entirely with numbers. This means that they are sorted alphabetically. An alphabetic sort looks at the first letter of the words (and numbers are counted as words in this case) and only looks at the second letter of the words if the first one is not enough to distinguish them. This means that the number 7 is alphabetically before 8, but alphabetically after 64. The computer looks at the "7" and the "6" of the 64 and sorts them just on the basis of those two "letters". Here's an example:
<SCRIPT> var x = new Array (7, 2, 3, 22, 71, 30); var count; x.sort(); for (count = 0; count < x.length; count++) document.write(x[count] + "<BR>"); </SCRIPT>

In this case, the output is as follows:


2 22 3 30 7 71

You see that, alphabetically speaking, both 2 and 22 come before 3, simply because "2" comes before "3" in the extended alphabet that computer programs

use. Similarly, "3" comes before "7" in that alphabet, so 7 comes later in the list than both 22 and 30.
How do we overcome this problem? Well, the obvious way is to write your own function that sorts the array. That way you can sort it numerically if it contains numbers. This is shown in Example 5a, and you can simply copy the function from that example and use it unaltered in your own programs.

However, there is an easier way. You may have spotted that it is numbers less than 10 that cause the problem. If we add a character "0" to the start of the numbers which are less than 10, then the numbers are sorted properly. Here is the previous example, with "0" added where necessary:
<SCRIPT> var x = new Array (7, 2, 3, 22, 71, 30); var count; for (count = 0; count < x.length; count++) if (x[count] < 10) x[count] = "0" + x[count]; x.sort(); for (count = 0; count < x.length; count++) document.write(x[count] + "<BR>"); </SCRIPT>

02 03 07 22 30 71

Although we have a "0" on the start of the numbers, they have been sorted correctly. It seems strange that JavaScript treats the elements of array x as numbers when it tests the condition (x[count] < 10), and yet as strings when it performs x.sort(). Aren't computers peculiar!

Don't add "0" to the start of all the numbers, otherwise you will be back to where you started and they will not be sorted correctly. Instead, only add "0" as necessary at the beginning to make sure that all the numbers are two "letters" long. Of course, if you have numbers which go into three or more digits, then you may need to add "0" or "00" or even "000" to the numbers as appropriate. This is demonstrated in Example 5b. Personally, I don't like this "adding 0" method. This is because it leads to problems with arithmetic. The trouble is that any number that starts with a "0" digit is interpreted by JavaScript as an Octal (base 8) number - yikes! This means that, although the numbers will sort correctly, as soon as you start performing arithmetic on them, you can into terrible tangles! My advice is to forget the "0" method and use the array to sort the numbers - or simply to stick to lists of numbers where this problem doesn't occur!
reverse() This works in a similar way to sort() except that it reverses all the elements. If an array originally contained the values 3, 1, 2, 5, 6 in that order, then the reversed array would contain 6, 5, 2, 1, 3. It is used in a similar way to sort(): myArray.reverse()

In this case, the warning about sort() does not apply. JavaScript is simply reversing the order of the elements, not comparing them in any way, so it makes no difference if the array contains strings, numbers or both.

JavaScript, Lesson 6 - Functions and Variable Scope

Lesson Objectives

Functions Parameters The concept of passing by value. The scope of variables: Global, or local to functions or blocks of statements. The return statement.

Recursive functions

What is a function?
A function is a group of instructions which has been given its own particular name. It can be called at any point simply by quoting the name of the function (with a couple of brackets). Perhaps an example may be useful:
<SCRIPT LANGUAGE="JavaScript"> var a = 1; document.write("I shall now call the function."); hereIsAFunction(); document.write("I can call it again!"); hereIsAFunction(); document.write("And yet again!"); hereIsAFunction();

function hereIsAFunction () { a++; document.write(" The value of a is now : " + a + "<BR>"); } </SCRIPT>

I have defined a function called hereIsAFunction and called it three times. The definition is at the end of the program (although it needn't be - you could put it at the beginning instead!) and starts with the word function, followed by the name and then a pair of brackets with nothing between them (I'll explain the purpose of those later). The two statements which actually make up the function (the instructions that the function actually carries out) are then enclosed within curly brackets. Please note that the brackets which come in the first line of the function definition do not have a semicolon after it. The function is called simply by using its name followed by the two brackets and then, as usual, a semicolon. The output produced by the program is as follows:
I shall now call the function. The value of a is now : 2 I can call it again! The value of a is now : 3 And yet again! The value of a is now : 4

The function firstly adds 1 to the value of a and then displays the message together with the (new) value of a followed by a line break. You should also notice that there is no special instruction to tell the computer where the main part of the program ends and the function starts - the keyword function is enough to tell it that!

Here is another program. This one has two function definitions in it, and, just for a change, I have put them at the start of the program:
<SCRIPT LANGUAGE="JavaScript"> function sum () { answer = a + b + c; } function average () { sum(); averageValue = answer / 3; } var a = 34, b = 51, c = 60, answer, averageValue; sum(); alert("The sum of the numbers is " + answer); average(); alert("The average of the numbers is " + averageValue); </SCRIPT>

So what's going on here, then? Well, the first function adds three variables, a, b and c and stores the sum in a variable called answer. The second function calls the first function (you can call a function from within another function!) and then divides the variable answer by 3 to give the average of the three variables. The main program creates the three variables with different values and then calls the sum() function. It displays the value of answer on the screen. Then it calls the average() function and displays the average value on the screen also. Neither function does any displaying on the screen itself, they just do calculations.

Parameters
The function sum() at the moment only adds the three variables a, b and c at the moment. In its present form, if you want it to add any other values you have to change the values of these variables. It would be nice if we could pass the values specifically to the function without having to set any variables as such. This is what parameters are for:
function sum (first, second, third) { answer = first + second + third; }

var first = 100, second = 23, b = 0, c = -44, temp = 750; sum(1.4, -3, 16); document.write("The sum is " + answer); sum(b, 150, c + 4.2); document.write("The new sum is " + answer);

sum(30 * c + 14, first, temp - second); document.write("The even newer sum is " + answer);

This program extract is rather complicated, but it does illustrate the point nicely. Take a look at the function definition - this time there are three names inside those brackets, with commas between them. These are the parameter names - we are going to pass this function three items (numbers in this case) and we will refer to them as first, second and third inside the function. We can use these numbers just as if they were variables, you notice that we add them together inside the function just as if they were variables. When the function is called in the main program, it is given three numbers inside the brackets. These can be simple numbers, as in the case of sum(1.4, -3, 16), where the parameter first is set to the number 1.4, the parameter second is set to the number -3 and the parameter third is set to the number 16. Alternatively, they can be variable names or arithmetic expressions, as in the case of the other function calls. It is also true that the names of the parameters within the function have nothing to do with the names of variables (or anything else) in the outside program - you'll notice that in the third function call, I have actually passed across the value of a variable called first, but I have passed it as the second parameter value, so inside the function for that particular call, the parameter second will have the value 100, not the parameter first. Geddit? Here I have shown how the parameters in the third function call match the function definition itself:

Pass by value
This program raises an interesting question. What happens to the value of temp?
<SCRIPT LANGUAGE="JavaScript"> var temp = 40; alert("The value of temp is " + temp); doesTempChange(temp); alert("The value of temp is " + temp);

function doesTempChange (temp) { temp *= 10; // This multiplies temp by 10; document.write("Inside the function, temp is " + temp); }

</SCRIPT>

The variable temp is set to 40 and then passed to the function as a parameter. I have even called the parameter temp inside the function, although I didn't have to (it would still have worked even if I had called it sausage). The function multiplies temp by 10 and then displays its value. When the function has finished, the value of temp is displayed a third time. So what does the program display? Well, since temp is set to 40, the first alert() instruction displays the value 40. The document.write() statement inside the function displays the value 400, since temp has been multiplied by 10. Again, no surprises there! However, the second alert() statement, which executes after the function has finished, displays the number 40 again. Why is this? The reason is that any changes made to a parameter inside the function are not reflected back into the calling program - the value of the variable is merely copied when it is handed to the function. This has to be the case - for instance, if the function doesTempChange() were called like this: doesTempChange(306); ... then how would the parameter value be changed? The fact that parameter values are only ever passed into functions, never out of them, is sometimes referred to as Pass by value. We say that the parameter has scope which is local to the function.

Variable Scope
The variables that we have been using up to now have been global variables (they have global scope). This means that they existed throughout the whole of the JavaScript program. Indeed, you can declare them within one program block (enclosed within <SCRIPT LANGUAGE="JavaScript"> </SCRIPT> tags) and they can easily be used within another program block. However, it is different for parameters and variables declared within functions. Consider this program:
<SCRIPT LANGUAGE="JavaScript"> function sillyFunc () { var a = 5000;

document.write("Inside the function, a = " + a + "<BR>");

var a = 10; document.write("Before the call, a is " + a + "<BR>"); sillyFunc(); document.write("After the call, a is " + a + "<BR>"); </SCRIPT>

This displays the following output:


Before the call, a is 10 Inside the function, a = 5000 After the call, a is 10

You will notice that the variable a declared within the function appears to have nothing to do with the variable a declared in the main program. It is set to 5000 (as proved by the statement displaying its value) but when the function has finished, the variable inside the function has disappeared and we are back to the original variable a with its original value of 10. The local variable only exists during the function call. While the function is executing, the global variable a (the one with the value 10 in the outside program) is shut away and can't be accessed. Instead, the local version takes over. When the function finishes, the local variable dies and the global one is released and becomes active again. Now we change the program ever so slightly:
<SCRIPT LANGUAGE="JavaScript"> function sillyFunc () { a = 5000; document.write("Inside the function, a = " + a + "<BR>"); } var a = 10; document.write("Before the call, a is " + a + "<BR>"); sillyFunc(); document.write("After the call, a is " + a + "<BR>"); </SCRIPT>

All I have done is take out the word var from the function definition. This means that there is no local version of the variable a, and setting a to any value within the function will have a permanent change on it. In this case, the output is:
Before the call, a is 10 Inside the function, a = 5000 After the call, a is 5000

This time the value has changed. There is only one variable called a, the global one. The question of whether a variable is local or global only arises if a function contains a variable declaration with the same name as a variable in the outside program.

The return statement


The return instruction only ever appears inside functions. It is used to pass values out of the function and back to the main program which called it (or to a calling function if it was called from another function). The return instruction is followed by the value to be returned, and it means that the function call can be used in place of a number or string. Perhaps an example will make all this clear:
<SCRIPT LANGUAGE="JavaScript"> function average (num1, num2, num3, num4) { var sum = num1 + num2 + num3 + num4; return sum / 4; alert("Yah boo sucks!"); }

var a = 2, b = 30, c = 78, x = 100; document.write("The average is " + average(a, b, c, x) + "<BR>"); </SCRIPT>

Look at the function call first. You will notice that it is has been put in place of a number or variable. We could just as easily have made the instruction document.write("The average is 52.5<BR>"); as the function average(a, b, c, x) "hands back" the number 52.5. The value to be handed back is sum / 4 as that is the expression that comes after the return statement. The variable sum is a local variable to the function and dies as soon as the function finishes, but its memory lives on as a quarter of its value is given to the main program. Whenever a function reaches a return statement the function finishes. Any other statements that come after it are ignored. This means that the alert("Yah boo sucks!") statement is never executed and the message never appears on the screen (fortunately!) Normally you wouldn't bother to put statements after a return statement in the function (it would be the last statement in the function), but I did in this case in order to demonstrate that the return statement finishes the function.

In the sample program below, I have rewritten a program from above using parameters and return. Compare it with the original, and you will see that this version is a lot more compact:
<SCRIPT LANGUAGE="JavaScript"> function sum (a,b,c) { return a + b + c; } function average (a,b,c) { return sum(a,b,c) / 3; } var a = 34, b = 51, c = 60; alert("The sum of the numbers is " + sum(a,b,c)); alert("The average of the numbers is " + average(a,b,c)); </SCRIPT>

Recursive Functions
As you have seen above, it is possible for a function to call another function. It is equally possible for a function to call itself. Such a function is called a recursive function. Let's take an example - the example they always use - is factorial numbers. Factorials are written using the ! symbol, and are defined as follows: 0! = 1 (by definition) 1! = 1 2! = 2 x 1 = 2 3! = 3 x 2 x 1 = 6 4! = 4 x 3 x 2 x 1 = 24 5! = 5 x 4 x 3 x 2 x 1 = 120 Get the idea? You will notice that a quick way to get any factorial is to multiply the number by the previous factorial, i.e. 5! = 5 x 4! Similarly, 9! = 9 x 8! and 103! = 103 x 102! This means that if you know a factorial you can easily get the next one in the series. Here we have the same idea as a function:
<SCRIPT LANGUAGE="JavaScript"> function factorial (n) { if (n == 0) return 1; else return n * factorial(n-1); }

// Display all the factorials from 0! to 10! var count; for (count = 0; count < 11; count++) document.write("The factorial of " + count + " is " + factorial(count) + "<BR>"); </SCRIPT>

The function takes a parameter and calculates the factorial of that number. Note that the first thing that the function does is test to see if we have reached the lowest number for which factorial is defined. This is the stopping condition of the recursive function and all recursive functions must have one. Suppose it had been missed out:
function factorial (n) { return n * factorial(n-1); }

Such a function, when called, would never terminate as it would endlessly be calling itself.

JavaScript - Lesson 7, Input Controls

Learning Objectives

The <FORM> and <INPUT> tags. The concept of events and tying an event to a function call. Reading values from input elements in forms. An example form Radio buttons Text areas Adding ONCLICK= handlers to other objects Hyperlinks and code

So far, the only way we have found for getting data into a JavaScript program has been the prompt() function. This is a clumsy way of doing it - the dialog box appears immediately that the page has been loaded, usually on top of some vital screen data (although there is nothing to stop you moving it around), and the only way to get rid of it is either to enter some data or click on Cancel. Wouldn't it be nice if we could include those small grey icons (often termed "buttons") and check boxes that you see on proper web sites! Well, this is easily achieved by including a form in a web page. A form includes several elements, each of which is a button, check box or a small slot for entering text. Furthermore, we can link each of these elements with its own

piece of JavaScript code, so that when the element is clicked on, JavaScript does something. This time it is the user, not the program, that decides when data is passed to the program, and in what order.

The <FORM> tag


This first part is not really JavaScript, it is HTML, but as you should know by now, JavaScript and HTML are intimately linked, so bear with me. The <FORM> tag is terminated by </FORM> and contains as much plain text and HTML as you like (tables, images, hyperlinks - whatever you like!) However, it also contains input tags, which usually take the form of <INPUT> followed by </INPUT>
<FORM NAME=myForm> Here is some text, and HTML tags <IMG SRC=mypic.gif> ... etc. <INPUT NAME=element1 TYPE="button" VALUE="Click on me!" ONCLICK="func1();"> </INPUT> Some more text and HTML if you want it! <INPUT NAME=typeInMe TYPE="text"></INPUT> I have put in some more HTML <HR><P> etc. </FORM>

Would you like to see what that form looks like? Here it is. Feel free to type in the text box and click on the button if it gives you a thrill:

Here is some text, and HTML tags you want it! etc.

... etc. Some more text and HTML if

I have put in some more HTML

All the items are strung together on one line as I didn't include any line breaks in the form definition (silly me!). Ignore the lines where I have put in random text and HTML - this was just to prove that I could. Concentrate on the <FORM> and <INPUT> tags. Note that the <FORM> has been given a name using the NAME= attribute. This is so that JavaScript will be refer to it. I have included two input elements, each named in a similar way to the form. The first is a button (as shown by the attribute TYPE="button") and the

caption that appears on the button is Click on me! (as shown by the attribute VALUE= which, for button inputs, specifies what appears on the button). The second control is an input slot (suitable for typing in text), as shown by the attribute TYPE="text". It has a name, but not a VALUE= attribute. These are only two types of the elements that you can include within forms - I shall describe a few more later!

The concept of events


You will notice that there is one part of the form that I didn't explain - the ONCLICK= attribute. This is what we call an event handler. An event is a rather grand word describing the most mundane happenings - when the user clicks a mouse on something, scrolls the web page up or down, moves from one page to another, or types some text into an input slot - these are all events. When an event happens, we want it to cause some action to take place, so we add an event handler. In the case of that button in the form above, we want the button to react to the user clicking the mouse on it, the CLICK event. The attribute ONCLICK= is followed by one or more JavaScript commands (complete with semicolon at the end) enclosed within quotation marks. Here is an example of an input element:
<INPUT NAME=x TYPE="button" ONCLICK="var a = 3; alert('a is ' + a);"> </INPUT>

(I have included that example on the left. The button is that small grey captionless slab. Go on, give it a click!) In this case, when the button is clicked on, the instructions that are carried out are
var a = 3; alert('a is ' + a);

(You will notice that single quotation marks within the alert() instruction as the whole thing is enclosed within double quotation marks - and we don't want JavaScript getting confused! Most of the time the ONCLICK= attribute is given a function call within the quotation marks, as a function can include as many characters as you like. For instance, if you had an input element defined like this:
<INPUT NAME=enterDetails TYPE="button" ONCLICK="trapDetails();"> </INPUT>

You could then include the following function definition inside your JavaScript program:
<SCRIPT LANGUAGE="JavaScript"> function trapDetails () { // Put in here all the things that you want to happen // when the user clicks on the enterDetails button } </SCRIPT>

Reading values from input elements


So, we now know how to activate a function when a button is clicked on. What about reading text from input elements? Forms are objects within the JavaScript program - they contain their elements as properties. The elements inside the forms are themselves objects, and they contain properties such as their value etc. For instance, consider that form above called myForm. This contained two input elements, one a text box and the other a button. The text entered by the user into the text box is given as follows: myForm.typeInMe.value It can be read just like a normal variable:
var textEntered = myForm.typeInMe.value; if (textEntered == "hello") document.write("Well done. You typed the magic word!<P>");

In fact, we can also access the value property of the other input element although we already know what this will be as it matches the caption of the button. Of course, there is no reason why we can't alter the caption on the button to anything else: myForm.element1.value = "Click on me or else!"; Similarly, you can alter the value property of the text box, which will change the text written in the text slot. Please note the full stops (periods) between the objects and their properties - these are exactly the same as the full stops that separate the words document and write in the document.write() command that you met in the first lesson.

Another example of a form

Here is a simple form which asks you for your name and then displays a welcoming message when you click on the "Here it is" button:
<FORM NAME=askName> Please enter your name : <INPUT TYPE="text" NAME=person SIZE=40> </INPUT> <BR><CENTER> <INPUT TYPE="button" VALUE="Here it is" ONCLICK="say_hello();"> </INPUT> </CENTER> </FORM> <SCRIPT LANGUAGE="JavaScript"> function say_hello () { var user = askName.person.value; if (user == "") document.write("Ah ha! I see you are the man with no name!"); else document.write("Welcome, " + user); document.write("<P>"); } </SCRIPT>

Work through this line by line to see how it works. I have not given the button a NAME= attribute, as we don't need to refer to the button as such within the JavaScript program. The person's name is read from the text box using the var user = askName.person.value statement. The function say_hello() is called when the user clicks on the button. I have added a SIZE= attribute to the text box to specify how wide I want it to be. SIZE=40 means that the slot is wide enough to see 40 characters that I have typed at any point - of course, I can type more, but after 40 characters, the text will "scroll". And here's the form itself: Please enter your name :

Radio buttons
These are nothing to do with radios. They are small circles which the user can click on to "set" them or "clear" them (i.e. to specify a yes/no option). When they are set, they are filled in black. When they are cleared, they are white. To create a radio button, use the <INPUT TYPE="radio"> tag. The caption to the button (i.e. the writing that goes with it), is displayed as normal text afterwards.

Radio buttons are similar to check boxes (which can also be set or cleared), with one essential difference. You can group several radio buttons together (by giving them all the same name using NAME=), in which case the user will only be able to select one of them at a time. If the user clicks on any of the buttons, then that one becomes set, and any other button that was set is cleared automatically. This is the normal way of using radio buttons:
<FORM NAME=quiz> In which country would you find the Great Wall of China? <P> <INPUT TYPE="radio" NAME="q" ONCLICK="guess(1);"></INPUT> England <BR> <INPUT TYPE="radio" NAME="q" ONCLICK="guess(2);"></INPUT> Russia <BR> <INPUT TYPE="radio" NAME="q" ONCLICK="guess(3);"></INPUT> China <BR> <INPUT TYPE="radio" NAME="q" ONCLICK="guess(4);"></INPUT> Australia <P> <INPUT TYPE="button" ONCLICK="markAnswer();" VALUE="Done"></INPUT> </FORM>

In which country would you find the Great Wall of China? England Russia China Australia Here we have four almost identical radio buttons - each within the same form and each with the same name. They all call the same function, but they each pass a different parameter value to the function. This is how the function knows which of the buttons was selected. The function is called when any of the radio buttons is clicked. The function might be called like this:
<SCRIPT LANGUAGE="JavaScript"> var myAttempt = -1; // -1 indicates "no valid answer" function guess (value) { myAttempt = value; } function markAnswer () { switch (myAttempt) { case -1 : document.write("Ah come on! You didn't try!"); break; case 1 : case 2 : case 4 : document.write("No that's wrong!"); break; case 3 : document.write("Well done!"); } } </SCRIPT>

In fact, I have put in two functions. The second one is activated when the "Done" button is clicked. It examines the value of the variable myAttempt and displays the appropriate message. You will note that the values 1, 2 and 4 all trigger the same clause of the switch statement. In fact, the function guess() only has one statement in it. It might have been more efficient if we had written the statements as follows:
<INPUT <BR> <INPUT <INPUT <INPUT TYPE="radio" NAME="q" ONCLICK="myAttempt=1;"></INPUT> England TYPE="radio" NAME="q" ONCLICK="myAttempt=2;"></INPUT> Russia <BR> TYPE="radio" NAME="q" ONCLICK="myAttempt=3;"></INPUT> China <BR> TYPE="radio" NAME="q" ONCLICK="myAttempt=4;"></INPUT> Australia

In this case, we wouldn't need the function guess() at all!

Text areas
A text area is similar to a text box, except that it is a large rectangular area on the screen into which the user can type as much text as required. When a text area is defined using the <TEXTAREA> tag, you should specify the number of vertical columns and horizontal text rows it should have: <TEXTAREA NAME="typed" COLS=30 ROWS=10> Any text that you include in here will appear inside the text area. Most programmers leave this part blank! Of course, the user can change the text in here, otherwise there would be no point! </TEXTAREA>

As you can see, this is one of the few input controls which isn't defined using the <INPUT> tag. The text typed by the user into the text area is obtained using the value property, exactly what we would expect: var masterpiece = myForm.typed.value; (In this case, myForm is the name of the form in which the text area was enclosed).

Adding ONCLICK= handlers to other objects


There is no reason why you shouldn't add event handlers to other objects: <IMG SRC=cat.gif ONCLICK="miaou();"> This will call the function miaou() when the image is clicked on. If you want to add an event handler to a hyperlink reference (a <A HREF=...> tag) then you should take an extra precaution. You should make the code within the quotation marks a function call which returns the value 0 or false as follows: <A HREF="" ONCLICK="return myFunc();"> Click on me! </A> Note that the hyperlink reference is left blank here. The function definition should be:
function myFunc () { // Normal statements in function here return 0; }

The reason for this is that the hyperlink needs to know whether to follow the link or not. If you just included the link as follows ... <A HREF="" ONCLICK="myFunc();"> Click on me! </A> ... then JavaScript would execute the function, and the web page would try to follow the hyperlink destination. In this case, the hyperlink has been set to an empty string - which confuses the browser no end! (In the case of my browser, it simply shuts down and you find yourself looking at the desktop!) Of course, you may actually want the browser to follow the link after it has carried out the function, in which case, your function needn't return a value, or it could return the value true or 1:
<A HREF="mainmenu.htm" ONCLICK="return fadeout();"> Main menu page </A> function fadeout () { var count; for (count = 255; count >= 0; count--) document.bgColor = count; return true; // Could be return 1; }

In this case, clicking on the function causes the background to fade from bright blue to black, and then the page changes to the main menu page.

Hyperlinks and code


Actually, there is an easier way to add code to a hyperlink to a code. You can specify the destination link as a JavaScript function call preceded by javascript: as shown in the following example: <A HREF="javascript:processNumbers();"> Process the data </A> There is now no need for the return false or the return statement in the hyperlink itself.

You might also like