Arrays in Javascript

Posted on 15-02-2013 17:22 by graham
This tutorial describes how you can create and manipulate array data type in Javascript.

What is an array


Array is a collection of objects put together in a specific order. The position of an object in the array is called index. In Javascript, arrays are represented by a data type called Array.

Javascript is a case-sensitive language, so remember that the Array data type starts with a capital letter.


Creating an array


To create an instance of the Array data type, use the following construction:
var names = new Array();

As you can see, differently than in many other programming languages, arrays don't need an initial size.

You can also provide the array that is created with a set of values:
var names = ["Hannah", "Lenny", "John"];

Adding elements to an array


To add elements to an array, simply choose an index at which you want to add them:
var names = new Array();
names[0] = "Jenny";
names[1] = "Mike";
names[2] = "Cathy";

This may be troublesome because it requires us to keep track of the current size of the array so that new elements are put at the correct index. Alternatively, you can simply push a value into the first free index:
var names = new Array();
names.push("Jenny");
names.push("Mike");
names.push("Cathy");

Different types of objects in one array


In Javascript, you can put objects of different types into the same array:
var items = new Array();
// add a number
items.push(22);
// add a string
items.push("Hello!");
// add an object
items.push(new Date());
// add another array
item.add(new Array());

Getting the size of an array


To get the size of an array, use the length property. Note - length is not a method, so do not put parentheses after it!
var numberOfNames = names.length;

Iterating over an array


The simplest way to iterate over an array is to use the classic for loop:
for (var i = 0; i < names.length; i++)
{
alert(names[i]);
}

Try it yourself and play around with the code in our sandbox.
Comments
Great, thanks for sharing this article.Much thanks again. Fantastic.
Added on 06-06-2013 21:23 by anonymous

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems