Introduction to JavaScript for Fortran Programmers

Introduction

The purpose of these notes is to introduce JavaScript to Fortran programmers to the extent that they will be able to write programs which can do most of the less computational intensive Fortran tasks, such as those associated with PS2h.

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.

Introduction to JavaScript

JavaScript (JS) is a sequential, procedural, algorithmic language. Although its syntax is rather different from Fortran, it has most of the same major structural elements.

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.

Creating and Running JS Programs

JavaScript is an interpreted language but unlike Basic or a spreadsheet it does not run in an interpretative environment. Thus JS programs are created using an editor, and then loaded into a web browser to be run.

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.

Examples 1

The first examples are JS versions of the basic programs used to illustrate the current Introductory Fortran course.

Hello World

This is the traditional first program of all C and Java programmers:
<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:

Hello, X is ...

This program introduces declarations, variables and expressions.
<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:

The program output is normally diplayed as HTML in a browser. HTML treats multiple spaces and/or newlines simply as separators. Forcing a newline in a web page requires the HTML linebreak directive <br>, and a blank line, or new paragraph, by the paragraph directive <p>.

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.)

Table of Squares

<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:

Real Roots of a Quadratic

<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:

As already noted the curly brackets can appear on the same or different lines from the related parts of the instruction.

There is also a single outcome condition e.g.:

if (value == 0) {
... // instructions
...
}  // end of condition 

The Bisection Program

<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.

JavaScript Arrays

The program below and here illustrates how single subscript arrays are created and 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:

Multi-subscript Arrays

JavaScript has only single subscript arrays. However, an array element may have any type, and may itself be an array. Two subscript structure may thus be created dynamically (all declarations in JS are dynamic) by defining each element of a single subscript array as an other array. The program below and here illustrates this.
<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)}

JavaScript Functions

Functions in Javascript are a very powerful tool and are used where other languages have built in elements.

At this point we will show only the conventional use of functions as might be appropriate to PS2h students.

Simple Function

This function shows the syntax of function definition and call, and illustrates that parameters are indeed passed by value.
<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>

Vapour Pressure Tabulation

For this program we have written the two functions shown below.
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.

JavaScript Objects, Arrays and `Call by Name'

Although, as we have seen, variables are called by value and so cannot be changed in a function, objects are passed by reference. It is thus possible to implement `call by name' by making the entity concerned an object, as described in the next section.

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:

Further Topics

The above notes should be sufficient to get you programming in JavaScript.

These links will provide information and examples on more advanced topics.