Understanding Javascript

By Nick Nagel

This document is intended to contribute to readers' understanding of Javascript.

The key to understanding Javascript is to have the insight that...

  1. Nearly everything in javascript is an object
  2. Javascript objects are hashtables
  3. Hashtable values are accessable using a syntax that superficially resembles array indexing notation in other languages (i.e., enclose the name of the property you want in square brackets following the object name)

This last fact might lead to some initial confusion working with arrays in folks coming to Javascript from some other programming languages.

Consder that arrays, like everything else in Javascript, are objects, and as objects they are, in fact, hashtables. This means that array elements can be added and retrieved by name *or* index.

Example 1: Indexed Arrays

The following creates an indexed array and iterates through it using a numeric index...

myArray = [1, 2, 3] ;
for( i=0; i<myArray.length; i++ )
{
    document.writeln( i + ". " + myArray[i] + "<br />"  );
}

Example 2: Arrays as Hashtables

While this next example assigns and retrieves array elements by name...

myArray               = [];  // same as myArray = new Array();
myArray["custName"]   = "Mickey Mouse";
age                   = -1;
myArray[age]          = 42;
document.writeln( "Customer Name: " + myArray["custName"] + "<br/>" );
document.writeln( "Customer Age: " + myArray[age] + "<br/>" );
document.writeln( "<br/><strong>Looping...</strong> <br/>" );
for( i in myArray )
{
    document.writeln( i + ": " + myArray[i] + "<br />"  );
}
    

The document Object

This last example uses these facts to better understand the Javascript document object. We can iterate over the hashtable properties of this object using the following script. Notice how the for construct has a built-in enumeration facility that allows you to iterate over the document properties...

for( p in document )
{
    document.writeln( "<tr><td><strong>" + p + "</strong></td><td>" + document[p] + "</td></tr>"  );
}
      

The output of the script follows...

Name

Value