J a v a S c r i p t  

Programming in
CPT 108 · Franklin College · Erich Prisner · 2002-2007

Javascript is an (interpreted) scripting language, developed jointly by Netscape and Sun around 1995.

A javascript in the head executes when it is called. If it is in the body part of the HTML page, it runs when the page is loaded. In any case, It must be inserted between these tags:

<SCRIPT TYPE="text/javascript">

It is also possible to use an external javascript, written in a separate file with extension .js (without the <SCRIPT> tag pair), and called by <SCRIPT src="scriptname.js">



In Javascript, you don't have to declare variables (but can do it using var x).

Data Types

In Javascript, you have so-called "loose typing". Even if you declare a variable you cannot fix the data type, which causes sometimes errors, since numbers may be interpreted as strings. Variables are case-sensitive.


Text is always included into quotation marks. If you want to insert quotation marks or other speciual characters into text, you use the backslash. \" is displayed as ". \& creates an ampersand, \\ a backslash, \' a single quote, and \n a new line. There are some others too.

Control Structures



should be defined inside the head in Jjavascript. ...


To write something on the text, use document.write("some text here"). Then there are dialog boxes which you activate by using alert("some text") or confirm("sometext") or prompt("some text","default value"). The second one has to buttons ("OK" and "cancel"), is of type Boolean and becomes true if the user clicks "OK". The third one prompts you for some input. Here are examples.


The whole rest of the line after // is disregarded. If you need comments of more than one line, include it between /* and */


See the separate page here for more detailed information.

HTML Objects

HTML DOM means Document Object Model. You can manipulate all styles and attributes of any HTML element with Javascript.


Javascript knows the event handlers

and many more. These event handlers are attributes in HTML tags, linking to JavaScript functions, like in onmouseover="function1()".

Handling Errors

try {
faulty code
catch(err) {
txt="There was an error on this page.\n\n Error Description: "+ err.description + "\n\n Click OK to continue.\n\n"

You can throw an exception, using the throw command.

Here are some interesting tutorials for JavaScript.