Example: Writing out the current date and time using dense arrays

A dense array excels over a normal one when it comes to initializing a rather large array with values upon declaration. In this section, we'll create a script that writes out the current date and time, in the following format:

Tuesday, July 28, 2005

The obvious task at hand is to first declare a series of variables that store the text "Monday", "Tuesday" etc and "January", "February", etc, since JavaScript is not human, and does not by default understand our calendar system. The remaining work is to match these text with the current date, and write it out.

The tedious part is the definition of these text, and the perfect job for arrays to handle- dense arrays, to be precise:

var dayarray=new Array("Sunday","Monday","Tuesday", "Wednesday","Thursday","Friday","Saturday")

var montharray=new Array("January","February","March","April","May",

The above code not only efficiently stores the text for the days of the week and months into two arrays, but allows us to directly use the JavaScript prebuilt functions date.getDay() and date.getMonth() as the index to reference the current date as represented by text, and write them out. Let's see just how this is done. The below shows the complete code that outputs the current date and time:

<script type="text/javascript">
var mydate=new Date()
var year=mydate.getFullYear()
var day=mydate.getDay()
var month=mydate.getMonth()
var daym=mydate.getDate()
//if the current date is less than 10, pad it.
if (daym<10)
var dayarray=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
var montharray=new Array("January","February","March","April","May","June","July","August","September","October","November","December")
//write out the final results
document.write("<b>"+dayarray[day]+", "+montharray[month]+" "+daym+", "+year+"</b>")

A code that may take a full page to write now has been reduced to one third, thanks to our buddy the dense array.