Notes 10
— print (last updated: Jul 15, 2009) print

Select font size:

These notes contain an introductory tutorial on the JavaScript language. If you are first learning JavaScript it is probably better to actually type in the code, rather than copying it. The syntax of JavaScript makes use of both parentheses "(" and ")" and curly brackets "{" and "}" for grouping. You have to be careful because the corresponding left characters and correspond rights have a very similar appearance in HTML-Kit. If possible, make the editor window's font size larger to differentiate their appearances.

Overview of the JavaScript language

JavaScript is a programming language which can access and manipulate every feature of an HTML document, indeed, it can access every feature of the entire browser (such as popup windows, the status bar, the history, etc. These browser elements are represented by so called objects within JavaScript. The objects are represented in a hierarchy called the Document Object Model (DOM). JavaScript also provides all the computational abilities of any standard programming language with structures for decision making, looping and creating user-defined functions.

JavaScript is maintained by the European Computer Manufacturer's Association consortium, and so its actual name is ECMA script, but everyone still refers to it as JavaScript. The Internet Explorer browser actually runs a variant called JScript, which is very close, but not identical to ECMA script (i.e. JavaScript). In general it's best to avoid the very latest features of these script languages because your audience's browser may not support them.

Using JavaScript in an HTML document is referred to as Dynamic HTML (DHTML) because it can give an HTML document a more dynamic behavior in various ways:

JavaScript bears some similarities to the Java programming language, but it is very different. The syntax of the languages are similar and they are both object oriented, but Java is more of a complete language whereas JavaScript is dedicated primarily to usage in a web browser.

Comments in HTML, CSS and JavaScript

Comments are any text written in conjunction with code (of any kind) which have no effect on the outcome of the code, and are only present to document the code written. When you write in JavaScript — or in any programming language, for that matter — it is common to add comments to the code because this helps others understand why you wrote what you wrote. Additionally, it helps you understand what you wrote when you review the code later, after some significant time period.

Both HTML and CSS support comments, although it is perhaps less common to comment these since you mostly "see" the code you wrote, in contrast to JavaScript programming, where much of the code goes "unseen."
Comments in HTML
These are any text (which may span multiple lines) of the form
<!--   HTML comments  -->
HTML-Kit can create HTML comments with the last icon on the right in the Document tab.
Comments in CSS
These are any text (which may span multiple lines) of the form
/*   CSS comments  */
They apply only within the style tags, or within an external stylesheet.
Comments in JavaScript
These are any text (which may span multiple lines) of the form
/*   JavaScript comments  */
or single-line text of the form:
//  JavaScript comments
JavaScript comments only apply within the script tags, or within an external JavaScript file.

The Object Model and Hello World Example

We remarked above that the browser features are accessed within JavaScript by so-called objects, and that the objects fall within a heirarchy. The very top level object in the Object Model is referred to as
window
The subobjects of window are Syntactically, we write window.document to refer to the document within the top level window object, however JavaScript allows us to omit the top-level "window." syntax.

In addition to subobjects, the JavaScript objects have action functions, or member functions, which are activated using the same "." syntax. The ones we'll start with (as does everyone else) are the write and writeln actions of the document object. Here is a simple JavaScript program created within the body of the document.

<script type="text/javascript">
<!--
  document.writeln('Hello')
  document.writeln('World')
// -->
</script>
Create this in HTML-Kit as follows:
  1. Open a new document and while positioned inside the body, create this: locate the JS icon in the Objects tab and click on it. It should create this template:
    <script type="text/javascript">
    <!--
    
    // -->
    </script>
    
  2. While positioned insided the script tags, type the JavaScript code:
    document.writeln('Hello')
    document.writeln('World')
    
  3. View the result in the Preview window.
This first JavaScript program illustrates a number of features:
  1. Using the script tags. Unlike the style tags, these can go almost anywhere within HTML document. The type attribute given here is not strictly necessary, since it will default to that value.
  2. The HTML comments appear in a very stylized way:
    <!--
    
    // -->
    
    They are needed for browsers which cannot recognize the script tag, i.e., those which do not do JavaScript. In that case they act like comments for the code inside. In the last line, the "//" starts a comment line for JavaScript; this is necessary to prevent JavaScript from trying to read the HTML comment terminator "-->" as JavaScript code.
  3. The line
    document.writeln('Hello')
    
    is called a statement. It consists of the action function call
    writeln('Hello')
    
    applied to the document object. The effect is to write this HTML string and then a new line character. In general an entire JavaScript program consists of a sequence of statements.

    The writeln function is called with a string 'Hello' as its parameter. Strings in JavaScript can be enclosed either by single quotes (' .. ') or double quotes (" .. ").
  4. The statement
    document.writeln('Hello')
    
    can be optionally followed by a semicolon (;). When this is used two statements can be put on the same line like this:
    document.writeln('Hello'); document.writeln('World');
    
    Nevertheless, it's generally a better programming practice to keep one statement per line.
  5. We could just as well written the writeln function in its fully qualified form as follows:
    window.document.writeln('Hello');
    

Types and operations in JavaScript

We saw in the above example the usage of the string 'Hello' and remarked that this is equivalent to the syntax "Hello". This entity is said to be of type string. The word type refers to how, and in what situations this entity can be used. JavaScript has these basic types: Entities of numeric type are numbers (with or without decimal points) such as 0, 3, 15, -36, 77.2, -15.266, etc. The boolean type supports two constants true and false. The object type supports a variety of things; one common example is the Date object. Objects are very common in JavaScript; they represent virtually every complex entity including the HTML elements themselves. Syntactically objects support properties and methods, delivered via the common syntax:
object.property
object.method()
The type array is used to represent lists of elements. The null value is common to all types and is often used to represent failure of an operation.

Operations

Operations are syntatic ways of combining entities. The most common of these are the binary arithmetic operators +, *, -, /, used to combine numeric entities in order to create arithmetic expressions (parentheses are also needed for expression syntax). In JavaScript the + operator is used for combining string objects by concatenating them. Thus we have the following:
4 + 5 = 9
"a" + "b" = "ab"
"4" + "5" = "45"
4 + "5" = "45"
This ambiguity can be confusing at first. The last of these combines a numeric with a string and indicates that the string type "wins out." In contrast the multiplication operator, "*", is not ambiguous and will always do (or try to do) multiplication by forcing string values to numbers. Thus:
4 * 5 = 20
4 * "5" = 20
"4" * "5" = 20

Try entering and running this JavaScript program (in the HTML body)
<script type="text/javascript">
<!--
document.writeln( 4 + 5 );
document.writeln( "<br />" );
document.writeln( "a" + "b" );
document.writeln( "<br />" );
document.writeln( "4" + "5" );
document.writeln( "<br />" );
document.writeln( 4 + "5" );
document.writeln( "<br />" );
document.writeln( "the sum is " + 4 + 5 );
document.writeln( "<br />" );
document.writeln( "the sum is " + (4 + 5) );
document.writeln( "<br />" );
document.writeln( 4 + 5 + " is the sum" );
document.writeln( "<br />" );
document.writeln( "the product is " + "4" * 5 );
// -->
</script>
The output is
9
ab
45
45
the sum is 45
the sum is 9
9 is the sum
the product is 20

The alert function

The alert function is an action function of the top level window object. It raises a special type of popup window which locks the browser until it is answered. This simple test program illustrates the point. Insert the following code into the HTML body:
<script type="text/javascript">
<!--
document.writeln( 'Before' );
alert( 'Testing' );
document.writeln( 'After' );
// -->
</script>
View the result in the Preview window. To complete the rendering you need to press the OK button in the popup. The other way to write this call is:
window.alert( 'Testing' );

Variables and the prompt function

A variable is an entity which can take on different values. Variables can be any word composed of letters, digits, and underscores, beginning with a letter or underscore. A variable name cannot conflict with some other reserved JavaScript name. Variables are almost always used in conjunction with the assignment operator, "=" in the form:
variable = value;
or
var variable = value;
The word var is a JavaScript reserved word which has the effect of declaring the variable, starting from this point on in the code. JavaScript permits variables to be used without declaring them but it is better to avoid this usage and always declare them. Here is a very simple example:
<script type="text/javascript">
<!--
var x = "Hello, "
var y             // still works with this line commented out
y = "John"
document.writeln( x + y + "<br />" )
x = 5
y = 6
document.writeln( x + y )
// -->
</script>

This program illustrates that variables can be assigned values of any types. The ability to do so is referred to as polymorphism; it is characteristic of so-called script programming languages.

The above program doesn't illustrate any real need for variables, since that output could easily be created without any variables whatsoever. The real need of variables is illustrated when the output depends upon a value set by user input.

The prompt function

One way to assign a variable from a user input is via the prompt action function. Here is a simple usage:
<script type="text/javascript">
<!--
var name = prompt( "Enter your name!", "YOUR NAME" ) 
document.writeln( "Hello " + name + ", how are you" ) 
// -->
</script>
View the result in the Preview window. The result is that a dialog box will pop up with a text field in which the user can type a line of text. You need to enter something in the popup window and press the OK button.

Try running it again and press the Cancel button to see what happens. Cancelling should somehow signal that we want to abort the writeln statement. We'll deal with this problem when we introduce decision-based programming.

Like the alert function, prompt is actually an action function of the window object, and so another way to write it is
window.prompt( "Enter your name!", "YOUR NAME" )
This function uses 2 string parameters. The first parameter "Enter your name!" is what is displayed in the prompt window. The second parameter "YOUR NAME" is the initial value of the text field.

If you pressed the Cancel button, the str variable is null. In Javascript, the null value is similar (but not identical to) a variable being undefined, which would occur if we never even tried to set its value, such as in the script:

<script type="text/javascript">
<!--
var name 
document.writeln( "Hello " + name + ", how are you" ) 
// -->
</script>
JavaScript can regard these two situations as being the same and we will see how to handle them later.

Numeric Inputs and the parseFloat function

Many programming features are based on combining numeric values.
<script type="text/javascript">
<!--
var str = prompt( "Enter a number", "" )   // prompt
var num = parseFloat(str)                  // string to numeric
//var num = str           // what happens when you use this line ?
var sum = num + num 
var product = num * num 
document.writeln( num + "+" + num + " = " + sum )     // output
document.writeln( "<br/>" ) 
document.writeln( num + "*" + num + " = " + product )   // output
// -->
</script>
View the result in the Preview window. Enter a number in the popup window and press the OK button. Then try running it again enter some non-numeric text to see what happens. Also try running it again and press the Cancel button to see what happens.

The parseFloat is one of the global functions (see global function table), i.e. not an activation function, which converts a presumably numeric string to its numeric value. What this means is that it changes type. This function is valuable for several reasons:
  1. the conversion to numeric is necessary when using "+", otherwise the operation is interpreted as concatenation
  2. if there are any error in the input you can find out immediately before going further with the computation

The cases where something goes wrong are, in some sense, the most interesting. If we press Cancel then the str variable is set to null and so parseFloat will fail. If we simply type return or enter some junk like xxx instead of a number, str will not be null, but parseFloat will fail.

What parseFloat does when it fails is generate a numeric value called NaN (meaning Not a Number). A NaN value can be combined arithmetically with other values but the combination will always result in NaN and so in either case we print out this:
NaN+NaN = NaN
NaN*NaN = NaN

Examples with Math functions

JavaScript supports additional computations using functions from the Math class. Up to this point we've seen two types of functions: Now we're introducing a third type of function, the class-based or static member functions. These use a syntax like this:
ClassName.function()
similar to methods like
document.writeln()
The difference is that they don't act on any object. The "." notation is merely a way to categorize the function as being part of a group of similar functions. In this way more than one class can use the same member function name without any ambiguity problem.

In the following example we will use the square-root function:
Math.sqrt
being a member of the Math class (see Math properties)
<script type="text/javascript">
<!--
var str = prompt( "Enter a number", "" )   // get a string
var num = parseFloat(str)                  // string -> numeric
var result = Math.sqrt(num)                // compute square root
document.writeln( "square root of " + num + " = " + result )   // output
// -->
</script>
Here we are using the square root function, Math.sqrt. Try running it with input 9, getting the answer 3. One problem is to give a decent answer to the square root of a number which is not a perfect square. For example, try the input 3, getting the output:
square root of 3 = 1.7320508075688772 
We really want to simplify the answer. The common way to do this is to round it to a certain number of decimal places. The Math.round function is used to round decimal numbers to the closest integer and so we have to modify its usage to get it to round, say, to 2 decimal places. The desired statement is this:
result = Math.round( result * 100 ) / 100
This is done prior to printing the answer, and so the entire program is this:
<script type="text/javascript">
<!--
var str = prompt( "Enter a number", "" )     // get a string
var num = parseFloat(str)                    // string -> numeric
var result = Math.sqrt(num)                  // compute square root
result = Math.round( result * 100 ) / 100    // round to 2 decimal places
document.writeln( "square root of " + num + " = " + result )  // output
// -->
</script>
With this additional statement in place, the output gives the simplified answer:
square root of 3 = 1.73 
We can use this technique to round to any number of decimal places:
round to 1 place: multiply and divide by 10
round to 2 places: multiply and divide by 100
round to 3 places: multiply and divide by 1000
...


© Robert M. Kline