Web Hosting
We've partnered with HostGator for reliable, affordable hosting starting at $3.95/mon. Use coupon code "javascriptkit25" for 25% off any package.

Overview of declaring dense arrays

There is an alternative way of assigning values to an array during declaration. The below illustrates this form:

var myarray=new Array("one","two","three")

The above is what's called a dense array, since it compresses the declaration and initialization of an array into one step. As you can see, we directly passed in the values of the array as parameters . To access the individual values inside, simply use the same old notation:

alert(myarray[0]) //alerts "one"

Access by name

Accessing an array element by name is also possible in dense arrays. This means a programmer can access the values of a dense array not only through the value's position within the array, like above, but also, through its name. For example, the below also alerts "one":

alert(myarray["one"])   //alerts "one"

There is no particular advantage to accessing a dense array through the value's name other than that it provides better documentation (others can more readily see which valuesis being accessed).

Lets now demonstrate the power of dense arrays by showing how it can significantly lessen the code required to create a script that writes out the current date and time.

Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.