Previous
Variables 
Next
Operators 
ABC of JavaScript : An Interactive JavaScript Tutorial
Arrays

Arrays

It is almost impossible to teach about arrays in JavaScript without referring to the JavaScript Object Model. But I want to teach the Object Oriented stuff at the end of the tutorial.

Creating an array is simple...

var numbers = new Array(3);

This will create a array called 'numbers' that can hold three elements. Now to fill it with numbers.

numbers[0] = 13;
numbers[1] = 0;
numbers[2] = 100;

The first line is numbers[0]. Notice the 0? One thing to remember about arrays is that arrays start with 0 - not with 1. So the first element of an array is its 0'th item, second is 1'st item and so on.

Another way of creating the same array is given below...

var numbers = new Array(13,0,100);

This will create the array and insert 3 elements - 13, 0 and 100. You can access any element of the array if you know its index. The below code will display the third item of the array - 100.

alert(number[2]);

The same method can be used to edit the elements...

number[1] = 1;

Although the above methods will create an array, this will be the most easiest way to create one...

var numbers = [13,0,100];

In JavaScript, one can use any type of variable as an array element - you can mix them up. You can even specify another array as an element of an array.

var items = ['JavaScript',1,12.3,"You get the idea"];

Now to see a full example on arrays.

Click on the Run button to see the result.

Previous
Variables 
Next
Operators 

Comments

Anonymous at 28 Mar, 2007 09:19
Ok, I don't know who runs this site, but GREAT JOB!

I love the examples given, and hope you keep it up!

Awesome!
Reply to this.
Arun Basil Lal at 21 Jun, 2009 01:18
See the about page. The page is well hidden, so no wonder you missed it!
Reply to this.
Anonymous at 18 May, 2008 09:03
nice work on creating this web page! Keep it up!@
Reply to this.
Sebastian at 26 May, 2008 03:41
thanks to who ever has come up with this tutorial...just what the doctor ordered
Reply to this.
Comment

Please dont enter you comments in this form - this is a fake form to confuse spamming bots. The next form is the real one.




Comment




Comment Formating : HTML tags a, strong, em, b, i, code, pre, p and br allowed. Other tags will be shown as code(< will become &lt;). Urls, Line breaks will be auto-formated.