If the notes are followed through and some examples are tried out this should also provide sufficient background to enable the reader to teach and supervise programming classes at our second year undergraduate level.
What JS does not have is any file operations. This severly limits the nature of the output which can be generated. On the other hand, JS can create WWW pages.
JS variables must be declared, but are untyped, the effective type being determined at run time from context.
JS is `object oriented'. This corresponds in practice to something like the ability to declare user types in Fortran.
JS has only functions whose arguments are always `call by value', and does not have procedures as such. However the use of objects enables functionality similar to `call by name' to be obtained.
JS programs are closely linked to HTML web documents, for example, the output from JS is normally viewed as a WWW page, and so a minimum knowledge of HTML is required to use JS. The easiest way to write and run a JS program is to embed it in a minimal HTML page. This takes the form of two HTML directives with the JS program between them and is illustrated in first of the examples below. Loading the page into an JS enabled browser causes the program to run and produce output which is displayed in the browser.
JS programs can also be put in a separate file, with extension .js which is then loaded by an HTML directive in the browser.
<script>
document.write("Hello World!") ;
</script>
This is in fact a one line program, the first and last lines
being HTML directives which identify the start and finish of
JS code.
If you left click on this link you will run the program in a new window. You can use the right mouse button to call up the `save as' option to save the program in your own filespace.
document.write ("Hello World!") is the JS equivalent of a procedure call. In object-oriented terminology it is the application of the method write to the document object with the parameter "Hello World!" It's syntax and effect are obvious.
Note that:
<script>
// Simple program with variables
var X ;
//
document.write("Hello World!") ;
//
X = 23.78 + 134 ;
document.write(" x is " , X) ;
</script>
The program is
here.
Note:
To get new or blank lines in the program output, simply put
these symbols in the string to be printed, e.g:
document.write(" <p> x is " , X) ;
This is done in
this version of the program. (Note that HTML is not
case sensitive so these and any other tags can be either upper or lower
case.)
<script>
// program squares
// calculate squares
var number, square
var max = 10
//
document.write('Squares of numbers from 1 to', max)
//
for (number=1 ; number<= max ; number=number+1 )
{
square = Math.pow(number,2)
// Note the funny way of writing powers!
document.write( '<br> Square of ', number, ' is ', square)
}
//
// end program squares
</script>
The program is here.
Note:
Unlike in Fortran there is no default of 1 for the last of these, but when a unity increment is required the shorter C-derived replacement for i=i+1 is just i ++ .
Slightly annoyingly, all mathematical functions belong to the class Math. and this (with a capital `M') must normally precede the names of all the standard functions, e.g. Math.sin(), Math.log(), etc. (The latter is natural log.) There is a way round this if you have a lot of expressions with functions.
<script>
// program quadratic
// solve a quadratic with real roots
var a, b, c, d, x, x1, x2
//
a = 1
b = 2
c = -3
//
document.write ('Solving quadratic:')
document.write (a, ' x**2 +', b, ' x + ', c, '<p>)
// check nature of roots..
//
d = b*b - 4.0*a*c
//
if (d<0) {
document.write ('Has complex roots.', '<br>')
} else {
x1 = (-b + Math.sqrt(d)) / 2.0 / a
x2 = (-b - Math.sqrt(d)) / 2.0 / a
document.write ('Roots are:', x1, x2, '<br>')
}
//
// end program
</script>
The program is here.
Note the JS conditional construction. The condition is the same as in Fortran. As written above:
There is also a single outcome condition e.g.:
if (value == 0) {
... // instructions
...
} // end of condition
<script>
var max, x1, x2, tries, x, f, f1, f2, expr, result
max=12
expr = "10-x"
x1 = 0
x2 = 100
for (tries = -1 ; tries<=max ; tries++)
{
if (tries==-1) {x=x1}
if (tries==0) {x=x2}
if (tries>0) {x=(x1+x2)/2}
result = x
with (Math) {
f = eval (expr) ;
}
document.write("f is " , f , "<br>")
if (tries==-1) {f1=f}
if (tries==0) {f2=f}
if (tries<=0) {continue}
if (f*f1>0.0) {f1=f ; x1=x}
else {f2=f ; x2=x}
document.write("x is " + x + "<br>" )
} // end for
</script>
The program is here.
This program introduces something which only an interpretive language can do.
The function eval with a string argument evaluates the string as an arithmetic expression, including evaluation of any variables whose names appear in it. This could have been used to simplify the logic of the program, which is a straight translation from Fortran, but uses a large number of conditions in order to have only one appearance of the function. A later version of this program which actually allows the user to type in the equation to be solved, will illustrate this.
Note the construction:
with (Math) { .... }
This essentially prefixes `Math.' to the names of any
mathematical functions which appear in the expression, allowing the
`normal' names to be used.
<script>
// generate some random numbers
var max=100
var sum, sum2, i
var x = new Array(max)
//
sum = 0 ; sum2 = 0
for (i= 1 ; i<= max ; i++)
{
x[i] = Math.random()
sum = sum + x[i] ; sum2 = sum2 + x[i]*x[i]
}
//
document.write( ' Mean of ', max, ' xes is :', sum/max)
document.write( '
Mean of sqrt(x) is ;', sum2/max)
</script>
Note:
var x = new Array()
<script>
var n=4
var i, j
var a = new Array(n) // makes a[1:n]
//
for ( i=1 ; i<= n ; i++)
{
a[i] = new Array(n) // makes each a[i] into an array a[i][1:n]
for ( j=1 ; j<= n ; j++)
{
a[i][j] = 100*i + j
}
}
//
document.write( ' The matrix is..
')
//
for ( i=1 ; i<= n ; i++)
{
for ( j=1 ; j<= n ; j++)
{
document.write (a[i][j], ' ')
}
document.write(i, '
')
}
</script>
The instructions required to create a square array starting at subscript
zero are thus:
var a = new Array(n)
for ( var i=0 ; i<= n ; i++) { a[i] = new Array(n)}
At this point we will show only the conventional use of functions as might be appropriate to PS2h students.
<script>
function test (x) {
x = x*x
return x
}
var x = 3
var y
y = test(x)
document.write('x is ', x)
document.write('<br> y is ', y)
</script>
function vpres (Tboil, T)
{ // approximate vapour pressure of substance with 1 atm
// boiling point Tboil at temperature T
var p
p = Math.exp (11*(1-Tboil/T))
return p
}
function decimals (x, n)
{ // function to round x to n decimal places e.g. for output
var mult
mult = Math.pow(10,n)
return Math.round(mult*x)/mult
}
However, these do not appear in the
program here because they are loaded in from separate files called
respectively vpres.js and decimals.js by the following
sequence.
<script src="vpres.js"> </script> <script src="decimals.js"> </script>The source of the program may be viewed here. The program also illustrates how HTML tags may be written to produce a tidy web page.
If we only need to return a single value from a function then there is no problem, since this may be returned as the function value and assigned to a variable on the LHS of an assignment. The most common situation where multiple values have to be returned is when the entity in question is an array. Conveniently, in JavaScript arrays are objects and so they will automatically be passed by reference, as running the program below illustrates.
<script>
function copy (out, inp)
{
for (var i = 0 ; i< inp.length ; i++)
{out[i] = inp[i]}
}
var x = new Array (0,1,2,3,7)
var y = new Array ()
copy (y,x)
for (var i=1 ; i< x.length ; i++)
{document.write (x[i], ' ')}
document.write('<p>')
for (var i=1 ; i< x.length ; i++)
{document.write (y[i], ' ')}
</script>
Note also:
These links will provide information and examples on more advanced topics.