JavaScript Arrays

From Techotopia
Revision as of 14:19, 15 May 2007 by Neil (Talk | contribs) (How to Create a JavaScript Array)

Jump to: navigation, search

In Introducing JavaScript Variables and JavaScript Variable Types we looked at storing data (such as numbers, strings and boolean true or false values) in memory locations known as variables. The variable types covered in those chapters were useful for storing one value per variable. Often, however, it is necessary to group together multiple variables into a self contained object. This is where the concept of JavaScript Arrays comes in.

What is a JavaScript Array

A JavaScript array is an object that contains a number of items. Those items can be variables (such as strings or numbers) or even other objects (such as Image objects or custom objects which you as a JavaScript developer have created). Once you have grouped all the items into the array you can then perfrom tasks like sorting the array items into alphabetical or numerical order, accessing and changing the value assigned to each array item and passing the group of items as an argument to a JavaScript function (see Understanding JavaScript Functions) by passing just the array object.

In this chapter we will look in detail at how to create and manipulate JavaScript arrays.

How to Create a JavaScript Array

A new instance of a JavaScript array object is created in the same way as any other object in JavaScript suing the new keyword. For example we can create a new array object instance called myColors as follows:

var myColors = new Array();

We can also specifiy the intial size of the array when we create it by passing through the number of elements that we require the array to hold as an argument to the Array() object constructor. For example, to intialize an array to hold 7 items:

var myColors = new Array(7);

Note: An array will grow automatically as new items are added so it is not necessary to specifiy at creation time the number of elements you believe the array will need. The decision as to whether to pre-allocate the initial size of the array is typically one of memory and speed. A mission critical application that needs to store a large amount of data in an array may not want the delay associated with waiting for the size of the array to be increased each time a new item is added. In this situation the array would be pre-initialized by specifying an initial size. This then has the trade-off that a large amount of memory may be taken up and not used right away. In practice it is usually acceptable to let array grow as items are added.


Initializing the Element of an Array