A Tour of Javascript, Part 1

Posted by Maciek Thu, 11 Aug 2005 20:01:00 GMT

Here’s a quick tour of some interesting things about javascript for casual programmers, with focus on usage in browsers. Javascript is seeing a bit of a revival lately as many programmers who have to use it in their day jobs gradually discover that it is a very interesting language.

Introduction

This tour includes many samples of javascript. To try the samples, open your favourite text editor, and paste the following document into it:

<html>
  <head>
    <title>Javascript examples</title>
    <script type="text/javascript">
    <!--

    -->
    </script>
  </head>
  <body>
  </body>
</html>

Whenever you want to try an example, simply paste the example code in between the area <!- and -> , while leaving a line or two above and below the example, for clarity. Save this file as javascript.html, and open it up in your favourite web browser (on any platform, I recommend Mozilla for javascript development, as it has a handy javascript console that gives you all sorts of useful information during testing). To try another example after your first, simply remove what you pasted before and replace it with the new example.

The Javascript Language

Objects, this, and flexibility:

Javascript allows for many of the OO (object oriented) features found in other languages, and although it does lack many powerful OO features, it does have some flexibility that allows for very quick scripting. For example, you can declare an Object and just start attaching fields and functions to it as you please:

var myobj = new Object();

myobj.favPhrase = "the quick brown fox";
myobj.favYear = 2004;
myobj.sayHello = function(abc){
  alert("Hello there, my favourite phrase is " + this.favPhrase + 
        " and my favourite year is " + this.favYear + 
        ". This function was called with the parameter " + abc + ".");
  };

myobj.sayHello(123);

The code listed above will pop up a message window that says:

Hello there, my favourite phrase is the quick brown fox and my favourite year is 2004. This function was called with the parameter 123.

Things to notice in this example:

  • You can attach fields to Object as you please
  • A function that is attached to an object accesses fields (variables) within that object by using “this.fieldname”. The “this” identifier refers to the Object to which the function belongs.

Code in javascript can modify itself in ways that are sometimes strange, but useful:

var myobj = new Object();

myobj.testfunc = function() {
  alert("The rain in spain");
  this.testfunc = function() {
    alert("Boot to the head!");
    this.testfunc = function() {
      alert("Nah nah!");
    }
  };
};

myobj.testfunc();
myobj.testfunc();
myobj.testfunc();

The code listed above will produce three consecutive alert windows that say “The rain in spain”, then “Boot to the head”, then “Nah nah!”. Each time a new alert window comes up, it represents the calling of a freshly overwritten testfunc() function in myobj. As you can see, javascript allows you to attach and overwrite functions, and write functions that overwrite and modify themselves willy nilly to your hearts content. This is a very useful feature.

Arrays and Iteration:

To declare a javascript array and put some things in it, we do something like this:

var a = new Array();
a[0] = "hello";
a[1] = "nurse";
alert(a[0]+" "+a[1]);

or this:

var a = new Array();
a.push("hello");
a.push("nurse");
alert(a[0]+" "+a[1]);

or this:

var a = ["hello","nurse"];
alert(a[0]+" "+a[1]);

All the above programs alert with “hello nurse”. Places in an array can have any kind of thing stored within them, even another array:

var a = new Array();
var a[0] = new Array();
a[0][0] = "Hello";
a[0][1] = "Nurse!";
a[1] = "Ity bity spider";

alert(a[0][0]+" "+a[0][1]+" "+a[1]);

Output: “Hello Nurse! Ity bity spider”

Javascript arrays, (as in PHP, for example), can be done by (key, value) like so:

var a = { "Rain":"spain", "Boot":"head", "Jimbo":"Jones" };

or:

var a = new Array();
a["Rain"] = "spain";
a["Boot"] = "head";
a["Jimbo"] = "Jones";

Interestingly enough, arrays of this kind can be accessed using more than one syntax:

var a = new Array();
a["Rain"] = "spain";
a["Boot"] = "head";
a["Jimbo"] = "Jones";

alert(a["Rain"]);
alert(a[0]);
alert(a.Rain);

Will all produce an alert window with “spain” printed in it. The last one of the three is of particular interest because it brings us back to Object, and let’s us introduce iterating (looping, in a manner of speaking). In javascript, as in PHP (before PHP5 at least), Object and Array are closely related, but within javascript differ in a few subtle details. With an array you are allowed to do something like this:

var a = new Array();
a["Rain"] = "spain";
a["Boot"] = "head";
a["Jimbo"] = "Jones";

alert(a.length);

for(var i=0;i<a.length;i++){
  alert(a[i]);
}

Which will produce 4 consecutive alert windows, “3”, “spain”, “head”, and “jones”. Notice that we have twice made use of a property of Array objects, length. (Notice also that it is not a function!). The length property contains the number of items stored in an array. Next, notice that we can also use a variant of the standard for loop, which is again reminiscent of PHP:

var a = new Array();
a["Rain"] = "spain";
a["Boot"] = "head";
a["Jimbo"] = "Jones";

for (var key in a){
  alert("The fieldname or key is: "+key+" and the value at that field is: "+a[key]);
}

The output of this program is in consecutive alert windows:

The fieldname or key is: Rain and the value at that field is: spain
The fieldname or key is: Boot and the value at that field is: head
The fieldname or key is: Jimbo and the value at that field is: Jones

This can be used to discover the field names or keys of an array if you do not know them ahead of time or are writing a function to extract all of them for whatever reason (and is useful for other purposes, as we shall see below). Note that if you had looped through this array using the for(var i=0; .. method in the previous example, you would not have the field names available to you, only the values of the array at those locations.

Any object in javascript can be “explored” or felt-out in this manner. For example, let’s use our Object from before:

var myobj = new Object();

myobj.favPhrase = "the quick brown fox";
myobj.favYear = 2004;
myobj.favFunc = function() {
  var pi = 3.14159;
  return pi;
};

for(var field in myobj){
  alert("this object has a field named "+field+" and its value is "+myobj[field]);
}

Output:

this object has a field named favPhrase and its value is the quick brown fox
this object has a field named favYear and its value is 2004
this object has a field named favFunc and its value is function() {
  var pi = 3.14159;
  return pi;
}

So Object seems to act a lot like an Array, allowing you to iterate the keys, see the values, even if they are functions (!). They’re the same, right? Well, no. Let’s try this:

var myobj = new Object();

myobj.favPhrase = "the quick brown fox";
myobj.favYear = 2004;

alert(myobj.length);

This brings up an alert containing the word “undefined”, which in javascript, is worse punishment than “null”! So Array objects are indeed a bit different from Object objects. You will notice, though, that an Array object contains all the functionality of an Object object. It could be said that Array is a kind of Object itself, which inherits all of Object’s abilities and properties.

Conclusion, and a taste of DOM

This concludes part 1 of this javascript tour. Here is a sample program to try. If you are the curious type, feel free to try to pry apart the objects you see used here by using iteration to try to discover fieldnames, hidden functions, and the general structure of things. Just paste this entire document into a new file and try it in your web browser:

<html>
  <head>
    <title>Javascript and DOM</title>
    <script type="text/javascript">
    <!--
      var myfunction = function() {
        var header = document.createElement("h1");
        header.appendChild(document.createTextNode("Hello world!"));

        var p = document.createElement("p");
        p.appendChild(document.createTextNode("The quick brown fox jumps over" 
        + " the lazy dog. Welcome to W3C DOM!"));

        var contentdiv = document.getElementById("content");
        contentdiv.appendChild(header);
        contentdiv.appendChild(p);
      };
    -->
    </script>
  </head>
  <body onload="myfunction();">
    <div id="content"></div>
  </body>
</html>

Check out the next article in the Javascript series

Posted in  | no comments | no trackbacks

Trackbacks: 0

Use the following link to trackback from your own site: http://schf.uc.org/articles/trackback/4

Comments: 0

Leave a response | RSS feed for this post

Leave a response

Toggle website and email fields