Some Basic JavaScript Info

There are two aspects to JavaScript as covered in JavaScript: The Definitive Guide. "Core JavaScript" refers to a standardized, general-purpose programming language and is covered in Part I of the book, with a language reference in Part III. "Client-side JavaScript" refers to the language as used in Web browsers and is covered in Part II, with Part IV as a language reference. Client-side JavaScript adds to the core language a large API that give access to the browser and its environment as well as to the web page and its Document Object Model. The API of client-side JavaScript is not so completely standardized, although it is much more so in modern browsers than it has been in the past.

Some Core JavaScript

For people who have programmed in Java, there is much about JavaScript that is familiar and much that is strange. The first thing that you will notice is that JavaScript statements don't have to be inside methods or classes. The second is that variables are not typed, and you can assign any type of value to any variable. All variables are declared using var as in:

         var x,y;
         var total = 0;
         for (var i = 0; i < 10; i++)
            total += i;

If you assign a value to an undeclared variable, the variable is automatically created as a global variable. This is almost never what you want, and as a matter of style, you should always declare variables using var.

Unlike Java, JavaScript is often happy to convert values from one type to another. For example, if you compare if (5 == "5"), the string "5" will be converted to the integer 5, and the answer will be true.

Fortunately, primitive types, expressions, and control structures are almost identical in JavaScript and in Java. Here are a few of the differences:

There are some other differences and additions that won't make sense to you until you know something about functions, arrays, and objects in JavaScript. But I encourage you to look through Chapters 2 through 6 of JavaScript: The Definitive Guide to get the full story.

Subroutines in JavaScript are always called functions (even when they don't return a value). Here is a sample function definition:

      function reverseString(str) {
         var rev = "";
         for (int i = str.length-1; i >= 0; i--)
            rev += str.charAt(i);
         return rev;

Note that just the name of the parameter is given in the parameter list. You could call this function by saying, for example, reverseString('Hello World'). The JavaScript compiler does not check that you provide the right number of parameters or that they are of the right type. In fact, sometimes it makes sense to have optional parameters, as in this array-sorting routine that can sort either an entire array or just a specified number of items:

        * Sort an array.
        * @param A An array of items.
        * @param n An optional parameter telling how many items to sort; if
        *          omitted, the entire array is sorted.
       function sort(A, n) {
          var count;  // how many elements to sort
          if (n)   // if n is defined (i.e. if it is provided as a parameter)
             count = n;         // only sort the first n items in the array
             count = A.length;  // sort the entire array
          for (var i = count-1; i > 0; i--) {
             var max = 0;
             for (var j = 1; j <= i; j++) {
                if (A[j] > A[max])
                   max = j;
             var temp = A[i];
             A[i] = A[max];
             A[max] = temp;

Note that Javadoc-style comments can be used in JavaScript; technically, it's a JDoc comment, with slightly different syntax. (NetBeans can pick up these comments and display them in its ContentAssist pop-ups when you are editing JavaScript.)

Some Client-side JavaScript

There are several places where you can put JavaScript code. Event-handling attributes in HTML tags specify JavaScript to be run when the event occurs. For example:

       <input type=button value="Click Me" onclick="respondToClick()">

Usually, only small segments of code, such as the function call used here, occur as attribute values. You can include longer code segments in <script> elements. For example:

   <script type="text/javascript">
       var pow = 1;
       for (var i = 0; i < 10; i++) {
          document.write("<p>2<sup>" + i + "</sup> = " + pow + "</p>");
          pow = pow * 2;

The document.write() method adds content to an HTML page as it being loaded. It should not be called after the document has been loaded; doing so will completely replace the page with the content that you write. For example, you shouldn't use document.write() in a function that is called in response to a user event.

JavaScript can also be stored in a separate file, which can be loaded into an HTML page with a variant of the <script> tag:

     <script type="text/javascript" src="file.js"></script>

The contents of the file are executed as the HTML document is being loaded. Usually, JavaScript files mostly contain things like function definitions that are meant for use elsewhere in the page.

Note that <script> tags can occur in the body of an HTML document as well as in the head. All the JavaScript on a page is considered to be part of the same program. For example, code in one <script> element can use variables and functions defined in another <script> element, or in a JavaScript file.

One of the main functions of client-side JavaScript is to program the dynamic behavior of a web page by manipulating its DOM (Document Object Model). Every element in the page becomes a JavaScript object. This is a very complicated subject, but here is a little bit of information: You can get the JavaScript object corresponding to the element with a given id attribute by calling the function document.getElementById(idValue). Once you have this object, there are all kinds of things you can do with it.

Supose that you have this silly looking empty <div> on your page.

       <div id='message'></div>

You can get a reference to the corresponding DOM object by calling document.getElementById("message"). You can then change the content of the div by assigning a value to the innerHTML property of this object:

        var msg = document.getElementById("message");
        msg.innerHTML = "<h2>Hello From JavaScript</h2>";

This would actually change the page to display the specified content inside the div. (This illustrates the disturbing fact that assignment statements can have side effects in JavaScript.)

A DOM element also contains a style object, which can be used to change the value of any CSS style property of the element. For example:

        var msg = document.getElementById("message");
        msg.innerHTML='<h2>Hello From JavaScript</h2>'; = "red"; = "rgb(80%,80%,80%)"; = "1cm"; = "italic";

Here, refers to the CSS property named background-color. Since JavaScript identifiers can't contain hyphens, the names of certain CSS properties have to be modified in this manner to be used in JavaScript.

Of course, this is only the barest of introductions, but it should give you some idea how JavaScript can manipulate the DOM to make web pages more interactive.

CS 271, Spring 2009