Working with Object Trees: Part One

JavaScript's ability to work with objects in hierarchy provides a variety of useful applications in the real world.

For example, you can create a folder tree like the one in Windows Explorer. In that application, you can navigate through your file directory system and open a directory by clicking the folder icon. Another example is an XML-based online help system or table of contents for your online books.

When working with objects in JavaScript, you don't have much choice other than to use the "array object." I'll begin this week with a review of the array object in JavaScript. Then in the following article, I'll explain the operations that you need to work with an object tree such as: create an object, append a child object to the root, search an object in the object tree, append an object to another object, and delete an object.

The array object

The array is the only data structure available in JavaScript for storing and manipulating ordered collections of data. Unlike arrays in some other programming languages, a JavaScript array can be used to store different types of data as its elements.

Also, as we get deeper into this concept, you'll see that you can create an array with or without specifying the number of elements. If you create an array without specifying the number of elements, the array behaves like a Vector object in Java where you can add elements arbitrarily.

The array object has one drawback: It's very hard to delete an element in an array.

Creating an array

Creating an array is as easy as assigning a variable with Array() using the new keyword.

var myArray = new Array();

Don't worry about specifying the number of elements because a JavaScript array is perfectly dynamic. You can add elements at any time after the array is created. However, if you must pre-size your array, for any reason, you can do that with the following statement.

var myArray = new Array(20);

The array element count starts from 0. If you specify an array with 20 elements like above, the array has the element index from 0 to 19.

An array also has the length property. The length property adjusts itself when you add an element with an index greater than the array size. For example, in the code in Listing 1, you first define an array with 20 elements, and then add the 21st element to the array. The length property adjusts accordingly.