This introduction is for students of the course
"GEM1501 - Problem Solving for Computing". Therefore
it contains some additional information on the system
being used and only those parts of Java Script which
are essential for doing the homework.
This introduction should give a short summary of the most
important facts. It does not make it superfluous reading
the books. Nevertheless, this introduction should make it
possbile for you to do the first assignments.
More material might be added to this introduction. If you have
specific questions which you believe should be addressed in a
short summary like this one, please mail them to
fstephan@comp.nus.edu.sg
You will be informed when the introduction is updated.
Everyone receives a unix account at the computer
sunfire.comp.nus.edu.sg. There is a new
procedure which permits students to create the account
by themselves. This
link
provides more information and one can from there or directly
go to a page to
request a new account.
This webpage also tells what
to do in the case that the password is forgotten.
The main purpose of the accounts is to do the assignments. If you
want to use your own laptop computer and find a way to display and print
webpages, this is also ok. But then you have to rely on yourself
for technical questions concerning your operating system.
After having created your account, you can log onto it
from any computer in the School of Computing.
In the laboratories
(COM1#B-10; Programming Lab 5), you find DELL Computers. You log into these
computers with your default account from the university, not with the unix
account. Then there comes up a Microsoft Windows Environment with
three columns of icons on the left side. One of the icons has
the name "SSH Secure Shell Client" under it. Click this icon.
There comes up a window with the headline
"sunfire.comp.nus.edu.sg - default - SSH Secure Shell".
This window has three rows of icons, click
the fourth icon in the second row ("Connect").
Now a menue with four rows
comes up. At "Host name", insert "sunfire.comp.nus.edu.sg";
at "User Name", insert the unix account name (which you received
at the helpdesk); the third row has the
default "22" and can be left unchanged; the fourth row can also
be left as it is (but you can also click "Password"). Having done this,
press the button "Connect". Sometimes an intermediate window comes
up which needs a "Yes"-button to be pressed. After his window or
directly after the login-window, a password-window comes up.
Enter in this window the password from your unix account.
Then a connection to your unix account is done through the main
window. You can increase the windows of this account by pressing
the tenth button in the second row ("New Terminal Window"), these
additional windows do not require a new password-dialogue. You can
also open a file-transfer window (which is yellow and not grey).
From unix-like computers, not having an "ssh" icon, you can
open an command-window ("xterm") and then the user with name
"astar" could log on his account with the command
ssh astar@sunfire.comp.nus.edu.sg
where "sunfire.comp.nus.edu.sg" is the name of the computer used.
Afterwards you are prompted for your password. The initial value
of the password is on the paper with your account name which you
have received.
In the case that you want to install an ssh on your computer,
please consult the page
You can change your password with the command "passwd". It asks first
for the old value of the password and then twice for the new value.
But make sure that you do not forget this new value.
Last year, many people had problems with passwords. In that case, the
general webpage
can be used to get the new password. In earlier years, it took sometimes
up to an hour; I have not tested it recently.
There is now a routine to make the homedirectory and to download all
assignments at once. If you do this routine, you do not have to download
any assignment again. You can just copy and paste the following five
lines from below into your ssh window and the corresponding commands
will set up the account for you.
You will then work inside the directory "public_html" of your account
and the assignments which are stored there can be viewed by your
browser. Please note that the routing "installgem1501" takes some time
to run and writes many messages onto the screen.
If you prefer to learn the commands better, you can also download
each assignment by yourself and do the following commands to create
a directory and to download each assignment by itself.
The first thing to do on your account is to create a directory for
your webpage and to go onto it.
mkdir public_html
chmod 711 ~/
chmod 755 public_html
cd public_html
Now you can download this page onto your computer and place it on
your webpage.
The "chmod" command makes everything on your webpage publically
readable. So you can look with your browser at your page. It is just
executed whenever downloading or creating a new file.
For more information on creating homepages, you can also consult the
corresponding
page of the School of Computing.
The wget command copies a file into your page. It needs the full
internet address of the file to get and produces a copy on this file.
Note that you have to remove the old file before calling "wget"
again. So, the command
ls -lt *
lists the files on your directory. The option "-lt" orders them such that
the newest files comes first so that you can remember their name for the
case that you have forgotten them. Furthermore, you can combine this command
with a "more" command in the case that you have more files then space on
the screen. Additional data can then be seen by pressing the space bar,
the listing of files can be terminated by pressing the key "q".
ls -lt * | more
In the case that you have downloaded the first asignment and you
have messed it up, you might need a remove-command to get rid of
this file. Here an example.
There are special program for modifying files, called editors. On
the system, there are two of them:
"pico"
and
"vi
In the case of "pico", you tell the editor in an
extra command which file to load. In the case of "vi",
one can enter the file to be edited together with the command
"vi" in the unix environment. While "pico" is self-explaining, you
should follow the above given link for "vi" for finding out how
to handle the editor.
pico javascriptintroduction.html
vi javascriptintroduction.html
Files can be printed using the unix lpr command. It is not necessary
to print homework to hand it in. It is sufficient to show the final
file in the laboratory session.
Browsers are programs to view webpages. If connected properly,
they can also be used to read and write emails and do other
communication behaviour. Webpages of certain companies are
connected to data bases which permit to do remote banking,
read timetables, look up telephone numbers and the more.
A further property is that browsers can interpret certain
programming languages. One of them is Java Script.
There are certain basic facts which should be known about
browsers.
The exact functionality of a browser depends on the company
which programmed it and the version. The browsers installed
at the School of Computing have the names "Mozilla"
and "Internet Explorer".
They have at the top one field to type in the address of
a webpage to view. The current one has the address
and can be found by either typing this name into the address field
or following the link on the course webpage.
The button "reload" or "refresh" is useful for seeing the effects
of modifications a webpage. The "backward" button permits to visit
the previously
visited page and the "forward" button permits to undo the effects
of pressing a "backward" button. The button "print" is for printing
the current webpage.
The symbol "x" in the upper right corner permits to kill the browser
window. Some browsers stop to work properly when loading a defective
Java Script webpage. You might need to kill the browser window, to
modify your file and then to open the page in the browser again if
this occurs.
Browsers support a bit the debugging of the program. The Microsoft
Internet Explorer finds the first Java Script syntax error
on a page. But to do use this facility, one has to change the
default settings.
Go to the menu "Tools" and then to the last row "Internet Options".
A new window "Internet Options" pops up. Go to the entry "Advanced"
in the list of subwindows on the top.
Check the box "Display a notification about every script error"
(sixth box under the entry "Browsing").
Press "OK" in the lowest row to finish.
This syntax-check was tested. It gave the following results:
* Forgetting a closing bracket at the end of a function gave
an error message telling the right fault but giving the
wrong location.
* Closing one bracket too much resulted in an error message simply
stating that there is a syntax error but giving the right location.
* A quote with only one citation sign was identified correctly.
* The usage of undefined variables was discovered correctly.
So it is recommended to use this option when developping programs.
Further options can be set in order to edit the program directly
with the browser and to use its debugging mode.
Furthermore, the browser Firefox can open under the entry "Tools"
an "error console" which displays the first Java Script error
on each webpage displayed.
Security settings for Internet Explorer.
(Note that this clicks to be done depend on the
browser installation of the Internet Explorer and vary from
installation to installation. The main instructions are given for
the installation in the labs.)
It turned out that the browsers have to be made
to accept "www.comp.nus.edu.sg" as a trusted side; otherwise some
assignments do not run properly. This can be done as follows.
Go to the menu "Tools" and then to the last row "Internet Options".
A new window "Internet Options" pops up. Go to the entry
"Security"
Click on "Trusted Sites" and then on "Sites".
(Some installations need then a further click on "Advanced" which is
subwindow on "Sites", not a direct subwindow of "Internet Options".)
The result of 3. is a menu to add trusted sites. Add the word
"www.comp.nus.edu.sg" in the field for adding urls and make
sure that the box "Require server verification ..."
is not checked. Havking done this, click the button
"Close" (or "Add" in some installations)
for the site entered.
Click the button "OK" on this and other popped up related
windows (might be one or two).
Webpages are mostly written in
Hypertext
Markup Language (HTML).
But this page contains also some parts in
Java Script.
Note that there is an other programming language with
the name Java, but Java Script shares with it just the name.
The Java Script commands can be placed inside or between certain
html-commands like this one which pops up a small window when you click
with the mouse on it:
The text for this button is the following.
<input type="button" value="This is a Button."
onClick="window.alert('The button was clicked');">
This environment itself is only needed for few advanced assignments,
but nevertheless it is always useful to know that certain things exist.
Note that Java Script knows two types of citation symbols for marking
quoted text. The simple and the double quote signs. It is equivalent
which one is used. This is done in order to nest the quotes. The command
"onClick" has a parameter in double quotes which tells to pop up a
window when the button is clicked, the text of this window is in
single quotes. Most Java Script commands have their own environment
which starts with the html-code word "script". Note that the description
of the language has to omit any space in the word "Java Script" since
the inventor of this programming language did not like spaces.
The text for this program is the following:
<script language="JavaScript">
<!--
document.write("Begin of Program.<br>");
document.write("Middle of Program.<br>");
document.write("End of Program.<br>");
/*This is a comment and ignored by the program*/
//-->
</script>
It just writes three lines into the webpage at the place
where it is placed. The commands "<script ... >" and
"</script>" tell the browser that between these two
lines is a Java Script program. After the first and before the
last line of this Java Script environment is the html-code for
comments on webpages which are ignored by browsers. For whatever
reason, these comments are necessary to make sure that the program
runs properly, at least for some browsers. The signs
"/*" and "*/" mark the beginning and the end of a comment
in Java Script. These comments can be used to write explanations
or to make the browser ignore parts of the program which are not
yet ready.
A detailed example: Euclid's Algorithm.
The next part of this tutorial contains Euclid's Algorithm from
the lecture in the original form with substractions. This
example will be used to explain the basic concepts, some of
them are then summarized again.
Programs use variables to store information. These variables
are modified during the running time of the program. As long
as variables contain just numbers or letters or short words,
it is in Java Script not necessary to tell the program which
of these cases hold. Below program computes the greatest
common divisor according to Euclid's Algorithm and outputs
the following line:
The text of the program is
<script language="JavaScript">
<!--
var x = 125; var y = 100;
while (x != y)
{ if (x > y) { x = x-y; }
else { y = y-x; } }
document.write("The greatest common divisor of 125 and 100 is "+x+".");
//-->
</script>
The algorithm has two variables x and y. It asigns the value 125 to
x and 100 to y. Then it runs through a loop while x and y are
different. The body of this loop consists of a conditional command
which says that y is substracted from x if x is greater than y and
that x is substracted from y if x is smaller than y. After the loop
a line outputs the content of x with some explanations. Note that the
loop is only left if x and y are equal. Therefore it does not matter
whehter one outputs x or ouputs y.
The handling of input is a bit more involved than that of output.
The easiest way to do this is to do it with windows which prompt
for the values.
Of course one would like to run the program with interactive input and
output. This can be done by windows which pop up. One can use the
"prompt" function to input and the "alert" function to output
This if fine for assignments, but not for this page. An idea to overcome
this problem is by putting the algorithm on an other webpage which
is executed only by clicking onto a link.
the prompting for input is delayed by using the "onClick" command
mentioned above. Here an example for Euclid's Algorithm with such
an environment. The idea is to put the algorithm in the extra
file "euclid.html". So you have to click on to the following link
to run the algorithm and the to click the "backward" button of the
browser to come back here.
The next lines are the complete implementation of Euclid's Algorithm
from that webpage. Explanations are found below the listing of this page.
<html>
<head>
<title>Euclid's Algorithm</title>
</head>
<body>
<script language="JavaScript">
<!--
var v; var w; var x; var y; var z; var endtext;
document.write("Euclid's Algorithm for positive integers.<br>");
x = prompt("Input first number");
y = prompt("Input second number");
x = Math.round(x); y = Math.round(y);
if (x < 1) {x = 1; }
if (y < 1) {y = 1; }
v = x; w = y; z = 0;
document.write(" x = "+x+" and y = "+y+".<br>");
while ((x != y) && (z < 1000))
{
if (x > y) { x = x-y; } else { y = y-x; }
z = z+1;
document.write(" x = "+x+" and y = "+y+".<br>");
}
if (x == y)
{
endtext = "The greatest common divisor of "+v+" and "+w+" is "+x+".";
}
else
{
endtext = "The algorithm did not complete in time.";
}
document.write(endtext+"<br>");
alert(endtext);
//-->
</script>
</body>
</html>
This is the content of the full file including the html-parts.
In the following, this example should be used to explain certain
ascpets of the algorithm.
<html>
This line confirms that the file is a html-file and may contain Java Script.
Every html-code starts with this line.
<head>
<title>Euclid's Algorithm</title>
</head>
These three lines of html-code hare the head of the file and say that the
title of the document is Euclid's Algorithm.
<body>
This line says that the body of the html-page starts.
<script language="JavaScript">
<!--
These two lines say that the Java Scrpit part starts and that the
part with the program is a comment with respect to the syntax of html.
var v; var w; var x; var y; var z; var endtext;
This line says that the program is using six variables with the
names v,w,x,y,z,endtext. The variables can either contain a number
or a string (= sequence of letters and digits) or a truth-value
which is either "false" or "true". In this program, the first five
variables will be used for numbers and the sixth one for strings.
This sixth variable endtext will contain the message displayed after
the algorithm has run successfully.
x = prompt("Input first number");
y = prompt("Input second number");
In these lines, the variables x and y receive the input from the user.
This input is collected in an extra window and the command for it has
the name "prompt". This command
displays the string in the brackets to the user and then passes the collected
value on to x and y, respectively.
document.write("Euclid's Algorithm for positive integers.<br>");
This line writes the title into the webpage which is referred to with the
Java Script word "document". The command "document.write" says that something
has to be written into the document.
x = Math.round(x); y = Math.round(y);
if (x < 1) {x = 1; }
if (y < 1) {y = 1; }
These commands make sure that x and y are positive integers. The command
"Math.round" transforms any number into the nearest integer.
So Math.round(2.000) = 2, Math.round(3.141592653589793) = 3,
Math.round(4.9999) = 5 and Math.round(8) = 8.
The next if-commands is a conditioinal command which sets x to 1 if
x < 1 and keeps x unchanged otherwise.
The last command does the same for y.
v = x; w = y; z = 0;
These three commands copy values into variables. So v and w take
the current values of x and y, respectively. z takes the value 0.
document.write(" x = "+x+" and y = "+y+".<br>");
This line outputs the current values of x and y. This permits to
keep track of the intermediate values during the algorithm on the
webpage. The plus-signs in this statement do not add numbers but do
append parts of texts. The variable-values are transformed into texts
haveing their decimal representation in this line. The four characters
"<br>" at the end of the line to be printed are an html-command.
It causes a linebreak, so the next text will go into a new line.
The same effect should be possible by using the command "document.writeln"
where "ln" stands for "line" but unfortunately this does not work with
all browsers.
The next lines are a loop. In loops commands are done iteratively.
The variable z is counted up such that the loop is done at most
1000 times. It is done as long as x and y re different and
z is less than 1000.
while ((x != y) && (z < 1000))
{
if (x > y) { x = x-y; } else { y = y-x; }
z = z+1;
document.write(" x = "+x+" and y = "+y+".<br>");
}
There are three commands inside the loop. The first one is a conditional
statement, which says that the value of y is substracted from that of x in
the case that x is greater than y and the value of x is substracted from that
of y otherwise. The next command increments the value of z by 1 for keeping
track of the number of times the loop is executed. The third line is a
statement to print the current values of x and y onto the webpage.
All the commands are insides braces (set brackets) in order to indicate
that all these commands belong to the loop.
Note that the loop is left if it has either been executed 1000 times
or the variables x and y take the same value. Only when x and y are
correct, the algorithm has found its valid output. Therefore there is
an if-statement such that if x is equal to y then the two statements
outputting the greatest commond divisor are done while it goes into
the second part following the word "else" if x and y are different.
Note that "x == y" compares the values of x and y while "x = y" writes
the value of y into the variable x.
if (x == y)
{
endtext = "The greatest common divisor of "+v+" and "+w+" is "+x;
}
else
{
endtext = "The algorithm did not complete in time.";
}
After this, the result endtext is output twice, into the document
and into a separate window. This is done by the following commands.
document.write(endtext+"<br>");
alert(endtext);
The difference between "document.write" and "alert" is that
"document.write" writes a line onto the webpage while "alert"
opens a small window and displays the value in this window together
with an alert-triangle. That triangle gives the name to this command.
The last four lines complete the file.
//-->
</script>
</body>
</html>
The first two of these lines say that the Java Script program ends.
The third line says that the body of the html-page ends and the
fourth that the html-code ends.
Variable Declaration.
The name of a variable should be a sequence of lower case
letters and be different from the following reserved words,
which have a special meaning in Java Script:
These reserved words have a fixed meaning and can therefore not be
used as names for variables. The following statements declare
variables with the names "australia", "newzealand", "singapore" and
"northamerica". After the declaration, to each of them is assigned
a value (which is the phone country code).
var australia; var newzealand; var singapore; var northamerica;
australia = 61; newzealand = 64; singapore = 65; northamerica = 1;
If one knows already the value of a variable when declaring it, one can
do both things in one step.
var australia = 61;
var newzealand = 64;
var singapore = 65;
var northamerica = 1;
var thisis = "phone country codes";
Note that "thisis" is permitted as a variable name while "this" is not
since "this" is a reserved word. Variables can be used to store numbers,
strings (sequences of letters and digits) or truth-values; for those
the words "false" and "true" are reserved. By the way, Java Script
identifies "false" with 0 and "true" with 1.
It is convenient to declare all variables at the beginning of the
program, but one is also permitted to do at somewhere else. In that
case, one has to make sure that the variable is not used before
its declaration and that the program is not running through the
declaration twice.
Input and Output through Subwindows.
Among the many methods to input and output data through subwindows,
the following are mentioned in this introduction.
x = prompt("Input first number");
y = prompt("Input second number");
yesno = confirm("Click OK to continue");
alert("The value is "+z+".");
document.write("The value is "+z+".<br>");
The command "prompt" opens a window. The parameter in the bracket is a
text displayed in this subwindow when asking for the input. The value
is returned. The command
x = prompt("Input first number");
displays the text "Input first number" in the subwindow. The input of
the user is assigned to the variable x. Note that if the user makes
a mistake and inputs a text instead of a number then the variable
has as a value a text and not a number. This might cause some problems
in the program later on. The command
yesno = confirm("Click OK for TRUE and CANCEL for FALSE");
requests the user to click in some window either a button with
the name "OK" or a button with the name "Cancel". If the user
clicks the button with the name "OK", then the variable yesno
receives the value true else the variable yesno receives the
value false. The text displayed is only for the user, it has
no influence on the way Java Script is assigning the value to
yesno. The command
alert("The value is "+z+".");
opens a window with a text in it which informs on the value of z.
For example, if z has the value 1024 then the window tells the user
the phrase "The value is 1024." and if z has the value "ABCDEFG" then
the window tells the user the phrase "The value is ABCDEFG." This
routine has originally be designed to display warning messages,
therefore the triangle in the window, but Java Script programmers
and text book authors like to use it just to display short pieces
of information for the user, even if they are not any warning at all.
The user has to confirm with pressing "OK" that he has seen the text
before the execution of the program is continued. Note that one can
also use the previously mentioned commands "prompt" and "confirm" for
combining the described input with outputting the text
between the brackets which accompanies the input request
on the window. The command
document.write("The value is "+z+".<br>");
is used for writing the same text into the current position of the
window of the Java Script program without opening a subwindow.
It is a standard command for doing outputs. The "<br>" at
the end is used to make a linebreak. One can put any html-commands
into the write statement and Java Script will carry them out when
writeing the statement. For example, the following statements
write texts in different fonts.
document.write("<b>First bold</b> and then normal. ");
document.write('<a href="euclid.html">Follow the link</a>. ');
document.write("<cite>At the end italic</cite>. ");
Note that the second statement is written with single quotes since it
contains a html-code which needs a name of a file in double quotes in it.
So using the single quotes for the Java Script argument make sure that
Java Script knows which quotes belong to which thing.
The output looks like this.
Basic Mathematical Operations.
The basic operations in Java Script are coded as follows where the
last one stands for computing the remainder of an integer division:
Note that the plus-signs "(3+1/8)" and "(3+1/7)" in the brackets is
adding numbers while the other plus-signs concatenate strings. It is
convenient that Java Script tries to find out by itself when a plus-sign
adds numbers and when it concatenates strings; but one needs to use brackets
to make sure that one is not misunderstood. If these brackets would
be omited, Java Script would succeed once to get what it should but
fail at the second time:
So in doubt use brackets to make clear what belongs to what.
Comparison Operators and Logic.
Often it is necessary to know logical conditions like
"Is a < b and c > d?" These logical expressions use the
truth-values "false" and "true". For example,
"3 < 8" is true and "3 > 8" is false. There are six basic expressions
to compare numbers and three operations to connect the outcome of
truth-values.
Operation Symbol Example of true condition Example of false condition
Equal == 8 == 8 3 == 8
Not Equal != 3 != 8 3 != 3
Greater > 8 > 3 3 > 8
Greater Equal >= 8 >= 3 3 >= 8
Less < 3 < 8 8 < 3
Less Equal <= 3 <= 8 8 <= 3
One can also connect logical values by "and", "or" and "not" but these
do not have that name in Java Script. They are written as
"&&", "||" and "!". Here a truth-table for the outcome of these
operations.
A B A && B A || B !A !(A || B)
false false false false true true
false true false true true false
true false false true false false
true true true true false false
So the following expression is true iff 3 is equal to 8 and
the value of x is different from y:
(3 == 8) && (x != y)
Since this expression is only true when both comparisons, that before
and that after the and-operator "&&" are true and since
the first statement is false, the whole expression has the value
"false", whatever the values of x and y are.
Conditional Statements.
One main application of truth-values are conditional statements.
In an if-statement, the truth-condition is put into brackets after
the word "if" and executed whenever this expression evaluates to
true. One can add a further statement with the keyword "else" which
is executed whenever the result of truth-condition is false.
This statement will always write "Ohh" and never write "Yeah"
since 3 is different from 8 and thus the condition is always false.
Some programming languages have the keyword "then" before the first statement
to write "Yeah" in order to make clear what happens, but in Java Script
this keyword does not exist. It is enough to close the bracket from the
truth-condition in order to know that the first statement starts.
By convention, both statements are put into braces (= curly brackets)
for better readability.
While Loops.
The keyword "while" says that a loop should be
executed as long as a logical condition is true. The logical condition
is always tested before entering the loop and then each time after the
whole body of the loop is executed. Thus it never happens that only
a part of the body is executed and thus the number of lines written
by the following loop is 6.
z = 0;
while (z < 3)
{
document.write("z is "+z+".<br>");
z = z+1;
document.write("z is "+z+".<br>");
}
This loop has the following output.
Note that the body of a loop is always put into braces (= curly brackets).
Note that it is important to make the condition of a while-loop to
become false eventually. Otherwise the program might never terminate
and the loading process of the browser might never be completed. In
particular, loops like the following should be avoided:
z = 0;
while (z < 3)
{
document.write("z is "+z+".<br>");
document.write("z is "+z+".<br>");
}
Here it was forgotton to count up the variable z and thus the loop
runs forever.
Do-While Loops.
If the condition at the beginning is false, the
body of the while loop is not executed at all. But one might want
that a loop is executed at least once. The following loop writes
square numbers while the square is less than a given number.
x = 0; y = 70;
do
{
document.write("The square of "+x+" is "+(x*x)+".<br>");
x = x+1;
}
while (x*x < y);
So the output are the square numbers which
do not exceed 70:
Note that there is a semicolon after the do-while loop because the last
character of the text is not a curly bracket but the normal bracket from
the logical condition after the while. Curley brackets are never followed
by semicolons.
If one replaces the value "70" by "-70" then the while condition at the
end is never satisfied, but the loop is nevertheless executed once and
gives the following output.
For Loops.
The idea of a For-Loop is to do something
for several values of $x$. For example, for x=0,1,2,3,4,5,6,7,8
print the value of x and its square. In Java Script, the formal
statement consists of the initial value of a variable, say x,
and at the end a condition to update x, say x = x+1. Thus,
the following two loops are equivalent.
for (x=0; x<9; x=x+1)
{
X; Y; Z;
}
x=0;
while (x<9)
{
X; Y; Z;
x=x+1;
}
Here "X; Y; Z;" stands for arbitrary statements in the body of
a loop. Ideally they should not change the values of x but this
is not enforced.
The above while loop for squaring numbers can also be written as a
for loop. In this for loop, now the cubic number are calculated.
But the condition for the body of the loop to be executed remains the same.
y = 70;
for (x=0; x*x<y; x=x+1)
{
document.write("The cubic value of "+x+" is "+(x*x*x)+".<br>");
}
This loop has the following output.
Note that for loops are equivalent to while loops, not to do-while loops.
So if one would set y to -70 instead of to 70, then no lines of output
would be given.
Switch Commands.
The Switch command permits to distinguish several cases depending of
the value of a single variable or expression. Here an example of
which gives a comment on a mark stored in the variable of the
same name:
switch(mark)
{
case "A": document.write("Above average, outstanding."); break;
case "B": document.write("Better than needed."); break;
case "C": document.write("Can pass well."); break;
case "D": document.write("Does narrowly pass."); break;
case "F": document.write("Failed."); break;
default: document.write("Error, this mark does not exist."); break;
}
The semantik of the switch-statement is the following: Inside the
brackes after the word "switch" is an expression computing a value,
most frequently just a variable which is read out. Depending of this
value, there follow a list of cases. The browser goes to the first
place where the value of the expression matches the value after the
word "case" and then executes all commands up to the word "break".
Furthermore, if the search for the cases does not succeed but the
word "default" is found, then browser executes the statements after
the word default up to the next occurence of the word "break". In
the following, a random mark is drawn a random, printed and then
sent through the above switch-statement:
The following example shows that one can also have several cases
for a sequence of commands. The program analyzes certain properties
of numbers like whether it is a square and how many divisors it has.
The program looks like this:
var x; var y = 32;
document.write("<pre>Numbers and divisors.<br>");
for (x=1; x!=y; x=x+1)
{
switch(x)
{
case 1:
document.write("The number "+x+" has exactly one divisor.");
break;
case 2: case 3: case 5: case 7: case 11: case 13: case 17:
case 19: case 23: case 29: case 31:
document.write("The number "+x+" has exactly two divisors");
document.write(" and is a prime number.");
break;
case 4: case 9: case 25:
document.write("The number "+x+" is the square of a prime");
document.write(" number and has exactly three divisors.");
break;
case 8: case 27:
document.write("The number "+x+" is the third power of a prime");
document.write(" number and has exactly four divisors.");
break;
case 16:
document.write("The number "+x+" is the fourth power of a prime");
document.write(" number and has exactly five divisors.");
break;
case 6: case 10: case 14: case 15: case 21: case 22: case 26:
document.write("The number "+x+" is the product of two");
document.write(" different prime numbers and has exactly");
document.write(" four divisors.");
break;
case 12: case 18: case 20: case 28:
document.write("The number "+x+" has exactly six divisors.");
break;
case 24: case 30:
document.write("The number "+x+" has exactly eight divisors.");
break;
default:
document.write("The number "+x+" has been forgotten.");
break; }
document.write("<br>");
}
document.write("</pre>");
The variable x runs through a loop from 1 to 31 and an expression tells
whether this number is something special; if it takes the same value as
y then the loop is no longer executed. Note that the default case is
never entered, but if one would set y to 33, it would enter the default
case when x is 32.
Functions.
Functions are subroutines. They can communicate with the main
program in several ways.
They are activated by a function call. Consider the following example.
alert("This is a warning");
This function displays a window displaying a warning text
when it is called.
Functions can have an output which might be used for further
purposes. Furthermore, they have inputs which are between brackets.
The following call has the input "Please enter an integer" and an
output which is passed on to a variable x.
x = prompt("Please enter an integer");
Functions can also modify variables used in the main program.
One can also define functions by oneself. The following function
computes the y-th Fibonacci number. It should be defined before
the first call in the programming text. The word "function"
preceeds the function name followed by the arguments in
brackets - just write "()" if there are no parameters passed to
the function. The body of the function is in braces (= curly brackets).
If it returns a result, one uses a local variable, here called z,
to store the result and adds the command "return(z)" at the end
of the function. The definition of a function is ignored as long
as it is not called.
var count = 0; var x;
function fibonacci(y)
{ var z; count = count+1;
if (y > 1) { z = fibonacci(y-1)+fibonacci(y-2); }
else { z = 1; }
return(z); }
x = fibonacci(20);
document.write("The 20-th Fibonacci number is "+x+"; ");
document.write("The computation needed "+count+" function calls.");
Functions can recursively call themselves as this example. It is
due to the programmer to avoid that a recursive call of a function
to itself ends up in an infinite loop.
The output will then be that the 20-th Fibonacci number is
10946 and that the computation called the function "fibonacci"
in total 21891 times.
Functions can also be used to define complex data objects. The
text book "Java Script - A Beginner's Guide" in Module 8, pages
189 to 221.
Arrays.
Arrays are a datatype which permits to store
values for further usage. They are created by a function
called "new Array" which has as input the number n of members
in the array. Then one can refer to the elements using square
brackets. The first element has the index 0, the last one the index
n-1. Here an example with an array to compute Fibonacci numbers.
This method is much faster than the usage of the function given
above.
var n = 25; var m;
var fibonacci = new Array(n);
for (m=0; m<n; m=m+1)
{
if (m<2) {fibonacci[m]=1; }
else {fibonacci[m]=fibonacci[m-2]+fibonacci[m-1]; }
document.write("Fibonacci["+m+"] is "+fibonacci[m]+".<br>");
}
The output of the program is:
Leonardo
Pisano Fibonacci wrote about this sequence of numbers
in his book "Liber Abaci" which he published in 1202.
Records implemented as Java Script Objects.
Arrays are a specific example of objects in Java Script. Another use
of objects is the concept of records. A record is a set of data
which is not so homogeneous that one would like to have it numbered
as item 0, item 1, item 2 and so on. Instead it is a structured object,
for example the full name plus the full salary of the person.
From the slides of the lecture, one can take the example of
Eberhard Ei and his company. The record on his person would then store
his name "Eberhard Ei" and the number 0.00 since
he does not get a salary from his own company. Introducing a variable
owner for these data, it could be constructed using the following
constructor function:
The keyword "this" refers to the object being constructed by the
function and the dot with the name after it says that one refers
to its first component with a dot followed by the word "fullname"
and to the second component with a dow followed by the word "salary".
The constructor function is then used in the main program with the
keyword "new" in front in order to signal that the variable receives
a new data record instead of some other values:
owner = new makeowner();
Then the following two Boolean conditions are true and the third one
is false:
Instead of creating every record with an own function, one could use
one function with parameters to create many records, this one is implemented
in this file:
function employee(fn,sl)
{ this.fullname = fn;
this.salary = sl; }
Having this function, one would then construct the record owner by the
command
owner = new employee("Eberhard Ei",0.00);
and could use the same function to construct an array containing the
data for all employees.
allemployees = new Array(4);
allemployees[0] = new employee("Anneliese Aal",1324.35);
allemployees[1] = new employee("Boris Bratling",1122.44);
allemployees[2] = new employee("Claudia Creme",4044.04);
allemployees[3] = new employee("Doris Dattel",1000.01);
The latter is implmeneted in the program below.
Adding the salaries is done as follows; the implementation
in this file is enriched by some "document.write"-commands which are
omitted here:
function salarysum()
{ var notednumber = 0.00; var ind;
for (ind=0;ind<allemployees.length;ind=ind+1)
{ notednumber = notednumber+allemployees[ind].salary; }
return(notednumber) }
The expression "allemployees[2].salary" would refer to the salary
of employee number 2 which is Claudia Creme. Instead of this fixed
reference, one can use the variable ind which for ind = 0,1,2,3
refers to the salaries of employees 0,1,2,3 one after the other.
So the loop does add up the salaries stored in the field
"allemployees[ind].salary" for the four employees. The entry
allemployees.length contains the length of the array allemployees,
thus one can use it as the upper bound in the for-loop. The
relevant part in main program is then introducing the variable
total and assigning the output of the function salarysum to it;
the result is written into the main window.
var total = salarysum();
document.write("<br>Total Amount is SGD "+total+".<br>");
Java Script permits, similar as C, to combine several steps in one.
This permits to write shorter programs and also to get faster execution
speed, in partcular by points 2 and 3 of the following four examples.
The speed is increased as the browser does in the abbreviated case
(fast loop) access the variables inside the loop less often than in
the nonabbreviated case (slow loop). Here the four examples.
Variables can receive values directly at the declaration:
Abbreviation Stands for
var x = 0; var x; x = 0;
If a variable in an update appears on bosth sides of an
assignment, then one can in certain cases save one occurrence
of the variable:
Abbreviation Stands for
x += 5; x = x+5;
x -= 18; x = x-18;
x *= y+z; x = x*(y+z);
x /= y+z; x = x/(y+z);
Note that the brackets are necesasry on the right hand side;
for example compare the results of the two variables v and w
after the loop
var v=1; var w=1; var u;
for (u=0;u<9;u++)
{ v *= u+1; w = w*u+1; }
at the end of this page.
The operators "++" and "--" add and substract 1 to and from
a variable, respectively, after it is read.
Abbreviation Stands for
c++; c = c+1;
c--; c = c-1;
while(c++<9) { X; } while (c<9) { c=c+1; X; }
Note that the name of the programming language "C++" refers to
this abrevation indicating that it is obtained by "incrementing"
C, that is, by adding the concpets of object-oriented programming
among other modifications.
The for-loop can also be interpreted as an abbrevation. Assuming
that A, C, D are statements and B is an Boolean expression, the
following are equivalent.
Abbreviation Stands for
for (A;B;C) D; A; while (B) { D; C; }
Note that the statement C comes after D and not before.
The statement D itself can consist of several statements
and so "D; " can actually be "{ D; E; }". Anyway, it is
good style to write "{ D; }" instead of "D;" in a for-loop.
For an example of loops with optimized versus nonoptimized code, follow this
link.