Main Page | See live article | Alphabetical index

JavaScript

JavaScript is an object-oriented scripting language originally developed by Netscape Communications under the name LiveScript but then renamed to "JavaScript" and given a syntax closer to that of Sun Microsystems' Java language. JavaScript was later standardized by ECMA under the name ECMAScript. The current standard (as of December 1999) is ECMA-262 Edition 3, and corresponds to JavaScript 1.5. Microsoft calls their version JScript.

Table of contents
1 Java and JavaScript
2 Usage
3 Environment
4 Language elements
5 Offspring
6 External links

Java and JavaScript

The change of name from LiveScript to JavaScript happened at roughly the same time Netscape was including support for Java technology in its Netscape Navigator browser. Consequently, the change proved a source of much confusion. There is no real relation between Java and JavaScript; their only similarities are some syntax and the fact that both languages are used extensively on the World Wide Web.

Usage

JavaScript is an object-oriented scripting language that connects through interfaces called Document Object Models (DOMs) to applications, especially to the server side (web servers) and the client side Web browser of internet applications. Many web sites use client-side JavaScript technology to create powerful dynamic web applications. It may use Unicode and can evaluate regular expressions (introduced in version 1.2 in Netscape Navigator 4 and Internet Explorer 4). JavaScript expressions contained in a string can be evaluated using the eval function.

One major use of JavaScript is to write little functions that are embedded in HTML pages and interact with the DOM of the browser to perform certain tasks not possible in static HTML alone, such as opening a new window, checking input values, changing images as the mouse cursor moves over etc. Unfortunately, the DOMs of browsers are not standardized, different browsers expose different objects or methods to the script, and it is therefore often necessary to write different variants of a JavaScript function for the various browsers.

JavaScript/ECMAScript is implemented by:

Environment

The Internet media type for JavaScript source code is text/javascript. To put JavaScript code in an HTML page, precede it with

 

The <!-- ... --> comment markup is required in order to ensure that the code is not rendered as text by browsers which do not recognize the <script> tag. <script> tags in XHTML/XML documents, however, will not work if commented out. Browsers that support XHTML and XML are modern enough to recognize <script>, so in these documents the code is left uncommented.

HTML elements[1] may contain intrinsic events to which you can associate a script handler. To write valid HTML 4.01, insert the following declaration for the default scripting language in the header section of the document.

  

Language elements

Variables

Variables are generally dynamically typed. Variables are defined by either just assigning them a value or by using the var statement. Variables declared outside of any function are in "global" scope, visible in the entire web page; variables declared inside a function are local to that function. To pass variables from one page to another, a developer can set a cookie or use a hidden frame or window in the background to store them.

Data structures

The primary data structure is an associative array similar to hashes in the Perl programming language, or dictionaries in Python, PostScript and Smalltalk.

Elements may be accessed by numbers or associative names (if defined with them). Thus the following expressions may all be equivalent:

  myArray[1], 
  myArray.north, 
  myArray["north"].

Declaration of an array:
 myArray = new Array(365);

Arrays are implemented so that only the elements defined use memory; they are "sparse arrays". If I only set myArray[10] = 'someThing' and myArray[57] = 'somethingOther' I have only used space for these two elements.

Objects

JavaScript has several kinds of built in objects, namely Object, Array, String, Number, Boolean, Function, Date and Math. Other objects belong to the DOM (window, form, links etc.).

By defining a constructor function it is possible to define objects. JavaScript is a prototype based object-oriented language. One can add additional properties or methods to individual objects after they have been created. To do this for all instances of a certain object type one can use the prototype statement.

Example: Creating an object

// constructor function
function MyObject(attributeA, attributeB) {
  this.attributeA = attributeA
  this.attributeB = attributeB
}

// create an Object obj = new MyObject('red', 1000)

// access an attribute of obj alert(obj.attributeA)

// access an attribute with the associative array notation alert(obj["attributeA"])

Object hierarchy can be emulated in JavaScript. For example:

function Base()
{
  this.Override = _Override;
  this.BaseFunction = _BaseFunction;
  function _Override()
  {
    alert("Base::Override()");
  }
  function _BaseFunction()
  {
    alert("Base::BaseFunction()");
  }
}

function Derive() { this.Override = _Override; function _Override() { alert("Derive::Override()"); } } Derive.prototype = new Base();

d = new Derive(); d.Override(); d.BaseFunction();

will result in the display:
Derive::Override()
Base::BaseFunction()

Control structures

If ... else

  if (condition) {
     statements
  }
  [else {
     statements
  }]

While loop

  while (condition) {
     statements
  }

Do ... while

  do {
     statements
  } while (condition);

For loop

  for ([initial-expression]; [condition]; [increment-expression]) {
     statements
  }

For ... in loop

This loop goes through all properties of an object (or elements of an array).

  for (variable in object) {
     statement
  }

Switch expression

  switch (expression) {
     case label1 :
        statements;
        break;
     case label2 :
        statements;
        break;
     default :
        statements;
  }

Functions

A function is a block with a (possibly empty) argument list that is normally given a name. A function may give back a return value.

  function(arg1, arg2, arg3) {
     statements;
     return expression;
  }

Example:
Euclid's original algorithm of finding the greatest common divisor. (This is a geometrical solution which subtracts the longer segment from the shorter):

  function gcd(segmentA, segmentB) {
     while(segmentA!=segmentB) { 
        if(segmentA>segmentB) {
           solution = segmentA - segmentB;
           }
        else {
           solution = segmentB - segmentA;
           }
        }
     return(solution);
     }

The number of arguments given when calling a function must not necessarily accord to the number of arguments in the function definition. Within the function the arguments may as well be accessed through the arguments array.

Every function is an instance of Function, a type of base object. Functions can be created and assigned like any other objects:

   var myFunc1 = new Function("alert('Hello')");
   var myFunc2 = myFunc1;
   myFunc2();

results in the display:

   Hello

User interaction

Most interaction with the user is done by using HTML forms which can be accessed through the HTML DOM. However there are as well some very simple means of communicating with the user:

Events

Text elements may be the source of various events which can cause an action if a EMCAScript event handler is registered. In HTML these event handler functions are often defined as anonymous functions directly within the HTML tag.

List of events

1 Blur is when the object is deselected or something else is selected instead.
2 Focus is when the object is selected, usually in a form.

See also http://tech.irt.org/articles/js058/

Error handling

Newer versions of JavaScript (as used in Internet Explorer 5 and Netscape 6) include a try ... catch error handling statement.

The try ... catch ... finally statement catches exceptions resulting from an error or a throw statement. Its syntax is as follows:

  try {
     // Statements in which exceptions might be thrown
  } catch(error) {
     // Statements that execute in the event of an exception
  } finally {
     // Statements that execute afterward either way
  }

Initially, the statements within the try block execute. If an exception is thrown, the script's control flow immediately transfers to the statements in the catch block, with the exception available as the error argument. Otherwise the catch block is skipped. Once the catch block finishes, or the try block finishes with no exceptions thrown, the statements in the finally block execute. This figure summarizes the operation of a try...catch...finally statement:

Here's a script that shows try ... catch ... finally in action step by step.

  try {
     statements
  }

catch (err) { // handle error } finally { statements }

The finally part may be omitted:

  try {
     statements
  }
  catch (err) {
     // handle error
  }

Offspring

A novel example of the use of JavaScript are Bookmarklets, small sections of code within browser Bookmarks or Favorites.

A similar programming language like JavaScript is used in Macromedia Flash. There it is called ActionScript.

External links