JavaScript - Array's Explained 
by The Sandman
4th March 1999 
here
 
Title
 
Understanding & Using Array's
Written by The Sandman 
 
Rating
( X )Beginner   ( )Intermediate   ( )Advanced   ( )Expert 
 
Introduction
Greetings Crackers, 

Like it or not, For loops & Arrays are a major part of most javascript routines, since they allow us to perform repetitive actions on a whole range of variables and arrays that would otherwise be impractical to do otherwise. 

Variables are just names we give to memory areas that are treated like letter boxes, they can for instance, hold either numeric or string data. Following on from this we have two types of main variables. 

Local variables are those variables that exist ONLY inside the function where it was created. Once program execution leaves the function then the variable(s) created inside this function are discarded and never used again. This makes good programming practice to use this kind of variable if it is not going to be needed elsewhere within the script. 

Global variables once defined, exist within the entire script, they can therefore be changed or read by any function within the script itself and is often used as a kind of 'counter' and or to maintain the results from having a string or number processed by one or more functions. 

The main disadvantage of using either Local or Global variables is that they can only hold one item of data at anyone time, which is fine in many circumstances but what if you were using 10, 20 or 100 items of data of say names, what then?. It would be impractical to create a 100 Global variables to hold a hundred names which would then make our script huge and very complex to maintain and run. In comes Arrays to our rescue. 

Arrays can be thought of as a huge Global variable, only this time it can be made to hold 1 or more items of data, rather like a spreadsheet in fact. Just like a Global or Local variable our Array will be given a name, and from there on this name will be treated like an index.  Once our Array has been created, internally it will be sub-divided into many smaller box's or cells as they are commonly called, these cells will each hold one item of data, either of numeric or string format and will then automatically be given a unique number that will be used to identify each cell. 

Think of an Array as being a set of box's all lined up together in your computer's memory, where each memory location is given a unique number that will identify it within our Array. 

In JavaScript, we can create any Array we wish using this format:- 

var Name_of_your_array=new Array(# of memory cells to create) 

 

Tools
Required
    
1 Pen.    
1 sheet of A4 paper.    
An open mind.    
 
About this
tutorial
I will try and explain the general principles of using and understanding how Array's work. Why they are so important to us and how we can use them to great effect.  

This tutorial is in no way a replacement for any JavaScript book that teaches the basics of learning JavaScript, it is simply a guide for use with these books.  

A good JavaScript book to have around is:-  
    
Laura Lemay's web workshop: Javascript  
 

T
H
E
 
E
S
S
A
Y
   
    
Suppose we wanted to create an Array called Alphabet, and assign to this Array, 26 cells, one for each letter of the Alphabet, then here's what we would do:  

In JavaScript we would type:  

var alphabet=new Array(25)  
  

At this point our Alphabet Array would contain 26 unique memory locations (starting from 0 to 25)  that would contain no data, ie, they would be un-initialized at this point and this is represented by the word NULL  

Array Name: Alphabet  
 

 Array Name: alphabet Contents of Cell 
alphabet[0]= NULL
alphabet[1]= NULL
alphabet[2]= NULL
alphabet[3]= NULL
...... NULL
...... NULL
alphabet[25]= NULL
   
  
In JavaScript we can access any 'cell' within our newly created Array simply by typing the Array name followed by [#] 
   
# = a valid number within the range of our Array.  In our example, we can use any number between 0 - 25. 

Before we can manipulate this array we must first 'initialize' it, in other words, give it some data so that we can then both read and change it during our script.. 

One method we could use is to assign each 'cell' manually, like this:- 

alphabet[0]=0 
alphabet[1]=1 
alphabet[2]=2 
alphabet[3]=3 
alphabet[4]=4 
alphabet[5]=5 
alphabet[6]=6 
alphabet[7]=7 
alphabet[8]=8 
..... 
..... 
alphabet[25]=25 
  
It works, but is a real pain to manage and follow, especially if your script become large and complex with these types instructions.. What is needed is a way to automate this process, by which we can condense 25 lines of code into just two or three lines.. 

Fortunately, JavaScript has a few solutions to this problem. One such solution is to use a FOR loop, where we can control the number of times a set of instructions is to be executed. 

Here's a revised method for initializing our Array named Alphabet with numbers from 0 to 25. 
  
for (a=0;a<=25;a++){  
alphabet[a]=a  
}  

The FOR statement tells Javascript that we wish execute 1 or more instructions contained within the { and }.  

a=0 We can control this FOR loop by initializing a variable, with a starting number, in this case we called our variable a and given it the starting value of 0 a=0. 

a<=25 Next, we want to keep checking to see if our variable a is still below the value of 25, if it is, then keep executing the loop. 
  
a++ Next, if a doesn't equal our ending value of 25 then we increase the value of a by 1. So if a equal 18 then a++ would now make a=19. 
  
That is all we need to control our FOR loop, all we need to do is to insert our one instruction that will automatically handle the initializing of our newly created Alphabet array.. 

alphabet[a]=a  

Notice here that we have replaced both the cell number and the value we want to insert into it with our variable a.  Think about it.. 

At the start of our FOR loop the variable a will be set to the value of 0, therefore our instruction alphabet[a]=a will be represented like this:- 

alphabet[0]=0 

This means, we want to access our Alphabet array and in 'cell' 0 we want to assign it a value of 0. 

Therefore, when the FOR loop gets repeated the variable a will be increased by 1 and so it will now equal 1. 

alphabet[a]=a  

So now the above instruction will be the same as though we had typed:- 

alphabet[1]=1 

Can you see what is happening here?. We are using a variable that is automatically increased by one by our FOR loop and we're storing this value in our Alphabet array. 
 
 

 Example #2 of our FOR loop
 
Of course it can work the other way, we can for example, reverse the sequence so that the value of 25 goes into cell 0 and the value of 24 goes into cell 1 etc etc.  To accomplish this all we need to do is to change the initial starting value of a, which as you remember began at 0 and change this to 25.  Next we change the checking of a so that instead of checking if a=25 we now change this so that it checks for a being decreased to 0. Finally, we must now stop the variable a from being increased by 1 each time the loop repeats and instead, have it decreased by 1 instead.. Confused?. Then take a look at our revised FOR loop:-  
  
for (a=25;a<=0;a--){   
alphabet[25-a]=a   
}   
 
   

Now that we have our array initialized we can drop this code right into a script function like this:-  

<script>  
var alphabet=new Array(25)   

function init() {  
for (a=0;a<=25;a++){   
alphabet[a]=a ;  
}   
}  
</script>  

On it's own, this function is useless to us, what we need to a way to read and update this array as well as being able to manipulate it's contents when ever we wish and with whatever value we choose.  Okay, we have our array filled in with some data and now we must think about how we want to use it.  For this tutorial we will keep things relatively simple in order to allow you to build upon further when you have this concept firmly fixed in your mind. 

For this tutorial we will begin by reading some chosen numbers from our array and then perform some simple operations on the data we receive.. 

Suppose we wish to add the values found in two cells from our Alphabet array then take away this total value using yet another cell value how might we do this?  

Well, lets first work out the problem then we can work on the solution.  

For this example suppose we wish to add the values found in cell 3 & 20, don't forget these values will be found in our Alphabet Array..  

Looking at how our Alphabet Array is initialized we know that by coincidence, cells 3 & 20 will contain the values 3 & 20 so therefore our result from adding these two values together will be 23.  Next, we want to select another cell and use it's value to take away from the previous result, which was 23. For arguments sake we will choose cell 6.  Therefore our end result should be 17.  

3 + 20 = 23  
23 - 6  =17  

We now know the steps to take, we also know the final answer to our original problem, now we must code this up in JavaScript.. Before we continue there is just one other consideration to make. If we don't tie our code to a button then our script will be executed each time our page is loaded, it is better therefore to give you, the User, the choice of wether to run this script. I will therefore use the Javascript statement onClick="init" to allow you to run this script whenever you wish.  

Lets go..  

<SCRIPT> 
<!-- 
var alphabet=new Array(25); 
var w; 
var x; 
var y; 
var z; 
function init() { 
for (a=0;a<=25;a++){ 
alphabet[a]=a; 
} 

w=alphabet[3]; 
x=alphabet[20]; 
y=w+x; 
z=y-alphabet[6]; 
alert("Value of w = "+w +"   Value of x = "+x +"  Therefore the total value of x+y ="+y +"              Final Result of y-Alphabet[6] = "+z); 
}//--> 
</SCRIPT> 

Lastly, we create a button using the form method  <POST> & </POST> tags to execute our init function. 

<FORM method="POST"> 
<INPUT type="button" name="B1" value="Click here" onClick="init()"> 
</FORM> 

The end result is this button. 

The final script may look at first, complicated and technical but if you remember that all we're doing is using two variables to hold the values from our Alphabet Array and then using two extra variables named y & z to manipulate the values then it should start making a little more sense.. Look.. 

var w;  // Will hold the value read from cell Alphabet[3] 
var x;   // Will hold the value read from cell Alphabet[20] 
var y;   // Will hold the result from performing 20+3 
var z;   // Will hold the final result from performing 23-6 
 

y=w+x;                 // Variable y equals w(3) + x(20) equals 23 
z=y-alphabet[6];  // Variable z = y(23) minus 6 equals 17 
 

Of course this example script is not perfect, we can easily do away with some, or all the variables and the script will still work. Perhaps you might want to experiment with this script and see what you can come up with?.  
 

Final Notes
Original format of this tut by (c) flipper (upg) 12/30/97 All rights reversed. 
way out
 
 

Page  by The Sandman  
Page Created: 6th March 1999