Categories:

Understanding and implementing arrays

So what are arrays? Well, they are an alternative way of defining variables that allow multiple variables to be quickly declared, painlessly. If you're a little confused at this stage, its ok.

Lets first quickly go over the "standard" way of declaring variables. Assuming we want to declare two variables to store the names of your in-laws...here's how it could be done:

<script type="text/javascript">
var x="Bob"
var y="May"
</script>

Pure and simple, right? Now, lets say you're really bored and want to store all of the known relatives in your family tree, all 50 of them, using JavaScript...we could do this:

<script type="text/javascript">
var x="Sam"
var y="Bob"
var n="Joe"
var v="Peter"
var m="May"
"
"
"
</script>

Pure, right? But not very simple. In order to define 50 variables, We had to think of a unique variable name for each one (such as x, y, n, and so on) while keeping track of which variable we're currently on. Well, with arrays, that kind of hassle is non-existent.

Just another friendly reminder: arrays are merely another way of defining variables, and nothing more. Lets first see how an array in general is created. To define an array, do the following:

var arrayname=new Array(# of variables to be created)

For example:

var x=new Array(50)

Now, to store the names into this array, we would do the following instead:

x[0]="Sam"
x[1]="Bob"
x[2]="Joe"
x[3]="Peter"
x[4]="May"
"
"
"
x[49]="George"

Are you starting to see the advantages arrays have over the standard method when declaring large chunks of variables?

Some advantages of arrays:

  • No need to provide each variable with a unique name.
  • Easier tracking and reference to any of the 50 variables.

As you have seen, individual variables within an array are referenced using brackets [ ] with an integer in there. You may also have noticed that the number in there started at 0, instead of 1. Why, you ask? Well, In the demented world of JavaScript, people like to count starting from 0; hours are counted starting at 0, the month of the year is too, so predictably, so are the numbers inside an array.

The biggest advantage of storing variables in arrays is undoubtedly when it comes to referencing them...you can now literally yell: " tell me who is the 25th person down my family tree!" and you're get an answer easily:

<script type="text/javascript">
alert(x[24])
</script>

That kind of versatility is quite difficult without arrays.