javascripts notes
TRANSCRIPT
-
7/28/2019 JavaScripts Notes
1/57
Creating a JavaScript programJavaScript 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 thetag as shown below:(The JavaScript program goes here)
Thetag at the end of the program tells the web browserinterpreting the file that the JavaScript program has finished and it should
expect more HTML tags to follow. Whenever the program comes across a
tag, then it will assume that the language used is JavaScript, so thelanguage="JavaScript" part of the tag isn't really necessary. The
program could just as easily be written as
(The JavaScript program goes here)
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 variousproperties (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 typesetc. but they still have properties and methods.
The document object
Here's the first object that you will meet -
-
7/28/2019 JavaScripts Notes
2/57
document. This refers to the mainscreen in the browser itself, the part
where the text and images appear. The
document has a property (among others)calledbgColor, which specifies whatthe 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:document.bgColor = "YELLOW";
You can add some more text and/or HTML tags here, of course.
You can add as many HTML tags to that as you like (but don't add abgcolor= part to thetag, of course, as we are trying to set this using
JavaScript). The word document is separated from thebgColor property bya 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 JavaScriptalmost 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 documentrather than DOCUMENT orDocument.
-
7/28/2019 JavaScripts Notes
3/57
bgColor is an example of a documentproperty. An example of its methods iswrite() 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:document.bgColor = "YELLOW";document.write("This should appear on a yellow background.");document.write("
");document.write("This is my second JavaScript program.");
You will see that you can include as many document.write() instructionsas you like, and thatwrite() is again separated from the word documentwith 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
in HTML causes a blank line to be inserted and enclosingthe HTML tag within a document.write() statement, it has the sameeffect. In fact, document.write() can duplicate the effect of any HTMLtag:
document.write("");document.write("");document.write("");
You do still need to enclose the tags within quotation marks. The following
would not work at all:
document.write();
Another property ofdocument is the lastModifiedproperty. Thiscontains the date that the document was last edited - it corresponds to the file-
edit 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 lastModifiedshould be written with all lower case lettersexcept for theMin the middle which should be upper case. lastModifiediswhat we call a read-only property - it can be displayed, and its value "read" by
-
7/28/2019 JavaScripts Notes
4/57
the program (for example, when testing conditions), but it can't be altered by
the program. The only way of altering the lastModifiedproperty is byediting 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 thevalue stored in it is 14.
Variables in JavaScript must be declaredbefore 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 namesmyName,MYNAME andMyname 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 butdon'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");
-
7/28/2019 JavaScripts Notes
5/57
then the word age would have been displayed on the screen. The value ofvariables can be changed at any point. Indeed, they can even be set to the value
of other variables:var x;
var y;x = 26;y = -109;document.write(x);document.write("
");x = 45.7;document.write(x);document.write("
");x = y;document.write(x);document.write("
");
The first number displayed on the screen is 26 (the value ofx). The secondnumber displayed is 45.7 (the updated value ofx - I didn't say the numbers hadto be whole numbers, did I?) and the last number displayed is -109 (afterx isset 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 ofxthat 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 endof
lines). For instance, the following lines:
var a;var second;var third_variable;a = 7;third_variable = 19;second = 2400;
can be rewritten asvar a, second, third_variable;a = 7;
-
7/28/2019 JavaScripts Notes
6/57
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("
");
var difference = first - second;document.write(difference);document.write("
");var product = first * second;document.write(product);document.write("
");var quotient = first / second;document.write(quotient);document.write("
");
The value ofsumis 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 beenset 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 variablevalues, 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 = 4;document.write(first + second);document.write("
");document.write(first - second);document.write("
");document.write(first * second);document.write("
");document.write(first / second);document.write("
");
-
7/28/2019 JavaScripts Notes
7/57
You can also mix numbers and variable values in longer arithmetic
expressions:
var answer;answer = 14 + sum - product;second = 10 * quotient - answer;
The value ofanswer is set to 14 + 16 - 48 = -18. The (new) value ofsecondis 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 of5 * temp1 is calculated first, and then the value of100 / temp2. The program then subtracts the first of these values from 40and adds the second of the values. Iftemp1 had the value 7.5 and temp2 hadthe 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 ofnew_answer to 25. Similarly, the following
document.write((x + 2) / (x * 2 - 5));
-
7/28/2019 JavaScripts Notes
8/57
would calculate x + 2 first, then the value ofx * 2 - 5 (doing themultiplication before the subtraction) and then divide the first number by the
second, displaying the answer.
String variablesThe 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 asotherwise it would display the word"proverb" rather than the value of
proverb. Variables can be re-assigned to different strings just as they can bewith 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 beenassigned 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
-
7/28/2019 JavaScripts Notes
9/57
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 (orstring 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 areusing 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 theirstring 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 documentproperties:
-
7/28/2019 JavaScripts Notes
10/57
document.write("Web page last changed on " +document.lastModified);
JavaScript - Lesson 2 Getting values into the program usingprompt(). Turning strings into numbers usingparseInt(),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 calledprompt() whichdisplays 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'sname", "Diane");
What you see is the following:
The prompt box carries a message - in this case, it's Please enter yourfriend's name and a default value, which isDiane. The idea is that theuser types the friend's name instead of this default value, and then click on OK.
http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part1%23part1http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part1%23part1http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part1%23part1http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part1%23part1http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part2%23part2http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part2%23part2http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part2%23part2http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part2%23part2http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part2%23part2http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part2%23part2http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part2%23part2http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part2%23part2http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part2%23part2http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part2%23part2http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part3%23part3http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part3%23part3http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part3%23part3http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part3%23part3http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part3%23part3http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part4%23part4http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part4%23part4http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part4%23part4http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part4%23part4http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part4%23part4http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part5%23part5http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part1%23part1http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part2%23part2http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part2%23part2http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part3%23part3http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part4%23part4http://richardbowles.tripod.com/javascript/section2/lesson2.htm#part5%23part5 -
7/28/2019 JavaScripts Notes
11/57
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 thescreen are passed to document.write() inside the brackets. We call these
parameters.
Theprompt() instruction takes two parameters: firstly, the message askingfor 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 isfriend_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", "");
-
7/28/2019 JavaScripts Notes
12/57
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 numbersThe problem with theprompt() instruction is it always returns astring. If weused it to get two numbers from the user and add them, we are going to run into
problems:
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);
If you enter 3 for the first number and 5.6 for the second, youshouldget 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 thestring 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 thatprompt() gives us into anumber. There are two instructions that we can use,parseInt() and
parseFloat().
The instructionparseInt()will take a string, either as a constant insidequotation 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) + "
");
-
7/28/2019 JavaScripts Notes
13/57
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". TheinstructionparseInt() then turns this into the number 10, which is thenadded to the number 4.55. The number is then concatenated with the "
" 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 + "
");
In this case, thefirst+ sign that the instruction comes across is the numeric
addition - it adds the numbers together. It is only afterthis 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
.
So what isparseFloat() then? Well, this is the instruction you would useif 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, ifparseFloat() is handed a whole number, it can still cope withit. 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 thedocument.write() instruction which correctly adds the variable to 100and 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
-
7/28/2019 JavaScripts Notes
14/57
problem with the addition program you saw above. Change the program to the
following, and it should work properly:
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);
Here we have included one instruction inside another. Theprompt()instruction produces a string, and instead of storing this string in a variable, it is
handed straight to theparseFloat() instruction which turns it into adecimal 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 asparseFloat(), soit 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, butthese are ignored when any mathematics is carried out). The instructioneval("2 * 2") works out the answer to this calculation and that becomesthe value ofx. The document.write(x) instruction displays the number 4on 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 valuedisplayed is 86.5.
The alert() instruction
-
7/28/2019 JavaScripts Notes
15/57
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 todocument.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 theword document or a full stop. This is because the alert() instruction is nota method belonging to the document object (Instead, it belongs to thewindow object, but that's another story ...)
The modulo operator
There is one mathematical operator that you haven't met yet. It is called moduloand is written as %. It gives the remainder when a division is carried out. Forinstance, the following program displays the number 2 on the screen, as 17
divided by 3 gives the answer 5 with a remainder of 2.
document.write(17 % 3)[
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 thefirst 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).
var first = 100, second = 23;alert(first / second);
-
7/28/2019 JavaScripts Notes
16/57
alert(first % second);
Comments
Often you will need to include small messages inside your program which arenot 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 followingthat 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 ratetax = turnover * x / 100; // Calculate tax paidnet_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 paidnet_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 /* tostart the comment and the symbol */ to end it. The example above could berewritten as follows:
var rows = 30; /* This line defines the number of rowsof pixels in the image. */
-
7/28/2019 JavaScripts Notes
17/57
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 youforget to include the */ at the end of the comment, the browser wouldtreat 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 aftercomments 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 23afterwards. 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
}
http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part1%23part1http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part1%23part1http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part1%23part1http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part1%23part1http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part1%23part1http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part2%23part2http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part3%23part3http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part3%23part3http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part3%23part3http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part3%23part3http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part3%23part3http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part3%23part3http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part3a%23part3ahttp://richardbowles.tripod.com/javascript/section3/lesson3.htm#part4%23part4http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part4%23part4http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part5%23part5http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part5%23part5http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part1%23part1http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part2%23part2http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part3%23part3http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part3a%23part3ahttp://richardbowles.tripod.com/javascript/section3/lesson3.htm#part4%23part4http://richardbowles.tripod.com/javascript/section3/lesson3.htm#part5%23part5 -
7/28/2019 JavaScripts Notes
18/57
The condition is a statement which may be true or may be false. If it istrue, the statements inside the { } are executed. If the conditions isfalse, thestatements 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. Ifthe 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), thenyou 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.writestatement 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 thescreen, 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 bignumber!");
It is useful to indent statements controlled by an if statement, as it gives aclear 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";
}
-
7/28/2019 JavaScripts Notes
19/57
If the sum ofa andb is less than 250, then two variables are set. The variablevar1 is set to a*b (whatever value that is) and var2 is set to the string "Toosmall". If the condition fails, then these variables aren't set. You will noticethat there is no need for an if statement to display anything on the screen
using alert() ordocument.write(). Although I tend to include these alot in my if statements, it is merely to demonstrate to the user whether thecondition 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 curlybrackets 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
-
7/28/2019 JavaScripts Notes
20/57
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 ifboth theindividual 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 jointcondition fails.
Similarly, you can join the conditions with || which means that the conditionwill 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 entirecondition 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 worksout 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 outb < 10 && c
-
7/28/2019 JavaScripts Notes
21/57
== 4 first. Ifb is less than 10 andc 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 eithera islarger 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 ifstatement 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 insidethe brackets succeed or fail?) and a comment where appropriate:
a > 6?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. Bytracing these brackets upwards, you should be able to see which opening curly
-
7/28/2019 JavaScripts Notes
23/57
brackets, {, they match. Needless to say, aligning the brackets carefully, as yousee 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 ifstatement 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");elsedocument.write("b is 10 or less, and a is not 6");
}
The switch statementThe command switch is a variation on the if statement.Instead of having a condition which can be true andfalse (i.e. the decision can go one of two ways), thevalue of a variable is tested. The switch statement canthen 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 variablemyVariable. IfmyVariable has the value 1, then the block of statements aftercase 1: is
carried out. When the program reaches the wordbreak at the end of the block,it skips all the other cases and carries on after the switch statement.
-
7/28/2019 JavaScripts Notes
24/57
Similarly, ifmyVariable has the value 4.6, then the block of statements aftercase 4.6: is carried out. Again, when the program reaches the workbreak, 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 ifmyVariable has the value -20.
The default part of the switch statement - which is optional - tells theprogram what to do ifmyVariable doesnt have any of the values specified.For instance, ifmyVariable had the value 6 or -100, then the default partof the switch statement would be executed. You will notice that thedefault part doesnt have abreak after it. This is because, if the switchstatement has a default part, then it is always the last item in the statement,
so it doesnt need abreak 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 togetherusing opening and closing curly brackets, { and }, the statements thatform 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 isequally obvious - it is the wordbreak that instructs the program to skipover the rest of the switch statement.
Note which parts of the switch statement require a semicolon andwhich do not. Like the if statement, there is no semicolon after thevariable being tested. The statements making up the cases have
semicolons at the end as usual.
-
7/28/2019 JavaScripts Notes
25/57
In fact, the wordbreak is optionalat 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 tosee whether you need to include
breakor not.
Here is another example of a switch statement. It comes from a program tocheck 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;
elsetax_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 didsay it was optional!). That is fine, as long as you are sure that the variable
taxBandwill have one of the specified values. If it doesn't then the switchstatement will do nothing, and execution will carry on with the statement after
the switch. Since nothing comes after the case where the taxBandis 3,
there is no need for abreak at the end of this statement either.
JavaScript Lesson 4 - Loops
The ++ notation Thewhile 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: thewhile loop, the do-while loop and the for loop.
http://richardbowles.tripod.com/javascript/section4/plusplushttp://richardbowles.tripod.com/javascript/section4/plusplushttp://richardbowles.tripod.com/javascript/section4/plusplushttp://richardbowles.tripod.com/javascript/section4/plusplushttp://richardbowles.tripod.com/javascript/section4/plusplushttp://richardbowles.tripod.com/javascript/section4/lesson4.htm#while%23whilehttp://richardbowles.tripod.com/javascript/section4/lesson4.htm#while%23whilehttp://richardbowles.tripod.com/javascript/section4/lesson4.htm#while%23whilehttp://richardbowles.tripod.com/javascript/section4/lesson4.htm#while%23whilehttp://richardbowles.tripod.com/javascript/section4/lesson4.htm#while%23whilehttp://richardbowles.tripod.com/javascript/section4/lesson4.htm#dowhile%23dowhilehttp://richardbowles.tripod.com/javascript/section4/lesson4.htm#dowhile%23dowhilehttp://richardbowles.tripod.com/javascript/section4/lesson4.htm#dowhile%23dowhilehttp://richardbowles.tripod.com/javascript/section4/lesson4.htm#dowhile%23dowhilehttp://richardbowles.tripod.com/javascript/section4/lesson4.htm#dowhile%23dowhilehttp://richardbowles.tripod.com/javascript/section4/lesson4.htm#for%23forhttp://richardbowles.tripod.com/javascript/section4/lesson4.htm#for%23forhttp://richardbowles.tripod.com/javascript/section4/lesson4.htm#for%23forhttp://richardbowles.tripod.com/javascript/section4/lesson4.htm#for%23forhttp://richardbowles.tripod.com/javascript/section4/lesson4.htm#for%23forhttp://richardbowles.tripod.com/javascript/section4/lesson4.htm#nested%23nestedhttp://richardbowles.tripod.com/javascript/section4/plusplushttp://richardbowles.tripod.com/javascript/section4/lesson4.htm#while%23whilehttp://richardbowles.tripod.com/javascript/section4/lesson4.htm#dowhile%23dowhilehttp://richardbowles.tripod.com/javascript/section4/lesson4.htm#for%23forhttp://richardbowles.tripod.com/javascript/section4/lesson4.htm#nested%23nested -
7/28/2019 JavaScripts Notes
26/57
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, { likethis }.
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 afterthem (with no intervening spaces). This simply means "increase the value of
this variable by 1". Here is an example:x = 2;alert(x); // This displays 2 on the screenx++; // Increase x by 1alert(x); // This displays 3 on the screen
The command x++ increased the value ofx, in this case, from 2 to 3. You willnotice that I did not use the keyword var in front of variable x when I firstreferred 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 declaredproperly 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. Thefollowing, 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 isplaced 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 wouldnot produce any output on the screen. The variable long_variable_namestarts off as 20, but is immediately reduced to 19 by the -- command. Thevalue of the variable y is then set to 19 + 10, i.e. 29.
-
7/28/2019 JavaScripts Notes
27/57
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 offirst, so that its valueincreases by 10. Similarly, the second instruction decreases the value of
secondby 23.4. Please note that there is no space between the +or- signand 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 besetto those values, not increasedordecreasedby 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 thatsame 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 value4.
Thewhile 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. Theformat of thewhile loop is as follows:
-
7/28/2019 JavaScripts Notes
28/57
while (condition){// Statements forming the body of the loop go here
}
Take a look at this example:
var x = 2;
while (x < 1000){ document.write(x + "
");x *= 2;}document.write("The loop has terminated!");
The variable x is initialised to 2. When the loop is first encountered, thecondition (Is x less than 1000?) is evaluated. It succeeds, so the loop is
executed. The value ofx is displayed, and then x is multiplied by 2. Then thecondition is tried again, with x now equal to 4. This is still less than 1000, sothe loop is executed again.
In fact, the loop carries on executing until the value ofx is set to 1024. Thecondition 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:
248163264128256512The loop has terminated!
Please note that the value of 1024 is not displayed on the screen. The reason isthat the multiply statement sets the value ofx 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 lessthan 1000. Since the test fails, the document.write(x + "
")statement is never executed again. -
7/28/2019 JavaScripts Notes
29/57
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 forthe 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 thewhile loop, but with one subtle difference. Thistime, the condition is tested at the endof each iteration of the loop. This means
that the loop must iterate at least once. It can never be skipped entirely. Theformat 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 enclosethe 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 ifstatements), but with the do-while loop, they are necessary. The following:
dox += 2;
while (x < 2500);
-
7/28/2019 JavaScripts Notes
30/57
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 aheader 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 thestartof 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 + "
");document.write("After the loop, count is " + count);
This loop starts by setting the variable count to 0. The test is carried out: Iscount less than 20? Yes it is, so the loop is executed. Thedocument.write() statement is executed ("The value ofcount is 0").The end-of-loop statement is carried out (count++) and the value of countgoes 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 notexecuted.
-
7/28/2019 JavaScripts Notes
31/57
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 itonly contains the single statement after the for header. The other
document.write() statement in the example above is only executed afterthe loop has finished - it displays the final value ofcount, which, you won'tbe 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 eachiteration takes place, the condition is tested to see if twice x plus 1 is (still) lessthan 100 more than x. If it is, then the main body of the loop is carried out. Youcan probably see that the condition could be rewritten as (x < 99) withexactly 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 theloop, the value ofa is used to alter the value ofx. This means that thecontinuing condition does eventually fail, and the statement after the end of the
loop (the alert() statement) is executed. If you work through the loop onpaper (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 withwhile ordo-
while loops. For instance, if one of the statements were removed from thatexample:
var x, sum = 0, a = 100;for (x = 20.5; 2 * x + 1 < 100 + x; a /= 2){ sum += x;}
alert("Sum is " + sum);
http://richardbowles.tripod.com/javascript/section4/demo1.htmhttp://richardbowles.tripod.com/javascript/section4/demo1.htmhttp://richardbowles.tripod.com/javascript/section4/demo1.htmhttp://richardbowles.tripod.com/javascript/section4/demo1.htmhttp://richardbowles.tripod.com/javascript/section4/demo1.htm -
7/28/2019 JavaScripts Notes
32/57
(I have kept the curly brackets in, even though they are now no longer really
necessary). In this case, although the value ofa is changed at the end of eachiteration of the loop, the value ofx is never changed, and the terminatingcondition 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 nestedloops. 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
-
7/28/2019 JavaScripts Notes
33/57
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 callmyArray (forwant 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 wordArray 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 roundones (). The elements of the array can be used anywhere where a normalnumber 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 orj in the examplesabove) or even expressions (such as 3 * count - 6 in the exampleabove). The expressions can include spaces - I tend to put them in to
make the expressions more readable.
-
7/28/2019 JavaScripts Notes
34/57
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 valueNaN, which isn't really a number or a string, butstands for "Not A Number". This is because another[4] hasn't beenassigned 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 betweeneach element:
for (x = 0; x < 10; x++){ document.write(values[x]);if (x < 9)document.write("
");
}
The if statement is in there to ensure that there is no paragraph break after thelast 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 0count = 0;do{ if (listOfNumbers[count] % 5 == 0)
sum += listOfNumbers[count]; // Add the value to the sumcount++;
}
-
7/28/2019 JavaScripts Notes
35/57
while (count < 83);
That could probably have been written more succinctly using a for loop, but Ilike to ring the changes.
Just because array elements start at 0 doesn't mean that you have to use everyelement. 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 specifyan 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 one-
dimensional arrays, except that each column of the array must be declared
individually:
var twoDimGrid = new Array(); // This declares the array itselftwoDimGrid[0] = new Array(); // This declares the first columntwoDimGrid[0][3] = 31;
// Now we can use the elements in the first rowtwoDimGrid[0][6] = twoDimGrid[0][3] - 32;twoDimGrid[2] = new Array(); // This declares the third columntwoDimGrid[2][6] = 26;
// Now we can use the elements in the third column
-
7/28/2019 JavaScripts Notes
36/57
Each column must be declared using the new Array() instructionseparately, 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 varcommand 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 seconditeration 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 arraycube[0][0] = new Array(); // This gives us a three dimensional arraycube[0][0][3] = "Hello";
// This is how we use a three dimensional array
-
7/28/2019 JavaScripts Notes
37/57
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 offirst are set up so that they holdthe numbers 1, 2, 3, etc. and then, the program copies every element offirstinto 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 thevalue 50 as well, as you might expect. The following instruction alters the vale
offirst[50]:
first[50] = 345.112;document.write("The value of first[50] is " + first[50] + "
");document.write("The value of second[50] is " + second[50] + "
");The instructions display:
The value of first[50] is 345.112The 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, re-running the program produces the following output:
The value of first[50] is 345.112;The value of second[50] is 345.112;
-
7/28/2019 JavaScripts Notes
38/57
Although we have only altered the value offirst[50],the value ofsecond[50] has changed also. What hashappened? Well, in fact, the statement second = firsthas made both the variables secondand first point to
the same set of numbers. Instead of being two separatevariables, 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 inJavaScript is an object - withproperties (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 valuein the array. This means that if you declared an array called stockName andset 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 elementsin 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 theelements of the array, the code would be:
sum = 0;for (x = 0; x < myArray.length; x++)sum += myArray[x];
http://richardbowles.tripod.com/javascript/lesson1.htm#objorienthttp://richardbowles.tripod.com/javascript/lesson1.htm#objorient -
7/28/2019 JavaScripts Notes
39/57
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 arestrings, 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 number7 is alphabetically before 8, but alphabeticallyafter64. 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:
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] + "
");In this case, the output is as follows:
2223
30771
You see that, alphabetically speaking, both 2 and 22 come before 3, simplybecause "2" comes before "3" in the extended alphabet that computer programs
-
7/28/2019 JavaScripts Notes
40/57
use. Similarly, "3" comes before "7" in that alphabet, so 7 comes later in the listthan both 22 and 30.
How do we overcome this problem?
Well, the obvious way is to write your own function that sorts the array. Thatway 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:
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] + "
");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 asnumbers when it tests the condition (x[count] < 10), and yet asstringswhen it performs x.sort(). Aren't computers peculiar!
http://richardbowles.tripod.com/javascript/section5/example5a.htmhttp://richardbowles.tripod.com/javascript/section5/example5a.htm -
7/28/2019 JavaScripts Notes
41/57
Don't add "0" to the start ofallthe 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 willsort
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 simplyreversing the order of the elements, not comparing them in any way, so itmakes 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.
http://richardbowles.tripod.com/javascript/section5/example5b.htmhttp://richardbowles.tripod.com/javascript/section6/lesson6.htm#part1%23part1http://richardbowles.tripod.com/javascript/section6/lesson6.htm#part2%23part2http://richardbowles.tripod.com/javascript/section6/lesson6.htm#part3%23part3http://richardbowles.tripod.com/javascript/section6/lesson6.htm#part4%23part4http://richardbowles.tripod.com/javascript/section6/lesson6.htm#part4%23part4http://richardbowles.tripod.com/javascript/section6/lesson6.htm#part5%23part5http://richardbowles.tripod.com/javascript/section6/lesson6.htm#part5%23part5http://richardbowles.tripod.com/javascript/section6/lesson6.htm#part5%23part5http://richardbowles.tripod.com/javascript/section6/lesson6.htm#part5%23part5http://richardbowles.tripod.com/javascript/section6/lesson6.htm#part5%23part5http://richardbowles.tripod.com/javascript/section5/example5b.htmhttp://richardbowles.tripod.com/javascript/section6/lesson6.htm#part1%23part1http://richardbowles.tripod.com/javascript/section6/lesson6.htm#part2%23part2http://richardbowles.tripod.com/javascript/section6/lesson6.htm#part3%23part3http://richardbowles.tripod.com/javascript/section6/lesson6.htm#part4%23part4http://richardbowles.tripod.com/javascript/section6/lesson6.htm#part4%23part4http://richardbowles.tripod.com/javascript/section6/lesson6.htm#part5%23part5 -
7/28/2019 JavaScripts Notes
42/57
Recursive functions
What is a function?
A function is a group of instructions which has been given its own particularname. 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: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 + "
");}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 thefirst 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 ofa and then displays the messagetogether with the (new) value ofa 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 isenough to tell it that!
http://richardbowles.tripod.com/javascript/section6/lesson6.htm#part6%23part6http://richardbowles.tripod.com/javascript/section6/lesson6.htm#part6%23part6 -
7/28/2019 JavaScripts Notes
43/57
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:
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);
So what's going on here, then? Well, the first function adds three variables, a,band c and stores the sum in a variable called answer. The second functioncalls 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 threevariables.
The main program creates the three variables with different values and then
calls the sum() function. It displays the value ofanswer on the screen. Thenit calls the average() function and displays the average value on the screenalso. 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 atthe 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 whatparameters 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);
-
7/28/2019 JavaScripts Notes
44/57
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 parameternames - we are going to pass this function three items (numbers in this case)
and we will refer to them as first, secondand thirdinside 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 ofsum(1.4,-3, 16), where the parameterfirst is set to the number 1.4, the parametersecondis set to the number -3 and the parameterthirdis set to the number
16. Alternatively, they can be variable names or arithmetic expressions, as inthe 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 thefunction for that particular call, the parametersecondwill have the value 100,not the parameterfirst. 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?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);
}
-
7/28/2019 JavaScripts Notes
45/57
The variable temp is set to 40 and then passed to the function as a parameter. Ihave even called the parametertemp inside the function, although I didn't haveto (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 hasfinished, the value oftemp is displayed a third time.
So what does the program display? Well, since temp is set to 40, the firstalert() instruction displays the value 40. The document.write()statement inside the function displays the value 400, since temp has beenmultiplied 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 anychanges made to a parameter inside the function are notreflected back into the
calling program - the value of the variable is merely copiedwhen 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, neveroutofthem, is sometimes referred to asPass 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 beenglobalvariables
(they haveglobal scope). This means that they existed throughout the whole of
the JavaScript program. Indeed, you can declare them within one program
block (enclosed within
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:
function sillyFunc (){ var a = 5000;
-
7/28/2019 JavaScripts Notes
46/57
document.write("Inside the function, a = " + a + "
");}var a = 10;document.write("Before the call, a is " + a + "
");sillyFunc();document.write("After the call, a is " + a + "
");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 havenothing 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 outsideprogram) 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:
function sillyFunc (){ a = 5000;document.write("Inside the function, a = " + a + "
");}
var a = 10;document.write("Before the call, a is " + a + "
");sillyFunc();document.write("After the call, a is " + a + "
");All I have done is take out the word var from the function definition. Thismeans that there is no local version of the variable a, and setting a to any valuewithin 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
-
7/28/2019 JavaScripts Notes
47/57
This time the value has changed. There is only one variable called a, the globalone. 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 passvalues 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 returninstruction 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: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) + "
");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
");as the function average(a, b, c, x) "hands back" the number 52.5. Thevalue to be handed back is sum / 4 as that is the expression that comes afterthe return statement. The variable sumis a local variable to the function anddies 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. Anyother statements that come after it are ignored. This means that the
alert("Yah boo sucks!") statement is never executed and the messagenever appears on the screen (fortunately!) Normally you wouldn't bother to put
statements after a return statement in the function (it would be the laststatement in the function), but I did in this case in order to demonstrate that the
return statement finishes the function.
-
7/28/2019 JavaScripts Notes
48/57
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 thatthis version is a lot more compact:
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));
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! = 12! = 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:
function factorial (n){ if (n == 0)
return 1;elsereturn n * factorial(n-1);
}
-
7/28/2019 JavaScripts Notes
49/57
// Display all the fac