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 
blog comments powered by Disqus