Skip to main content

One-Dimensional Arrays

An array is a type of variable; therefore you need to declare it before using it. In fact, unlike regular numeric, string, or Boolean variables that don't really need to be declared (but always should be), JavaScript insists that you declare an array in advance. You use the var statement again, but this time with a slightly different syntax.There are four syntaxes you can use. Let's start with the simplest:

var Array_Name =  new Array()

Where Array_Name is the name you want to use for the variable. In JavaScript, an array is actually an object, so what the new keyword is doing here is creating a new Array object. The Array() part of the statement is called a constructor because its job is to construct the object in memory. For example, to create a new array named code_listings, you'd use the following statement:

var code_listings = new Array()

The second syntax is useful if you know in advance the number of values (or elements) you'll be putting into the array:

var Array_Name =  new Array(Number_Of_Values)

Where Array_Name is the name you want to use for the variable and Number_Of_Values is the number of values you'll be placing into the array. For example, here's a statement that declares a new code_listings array with 16 elements:

var code_listings = new Array(16)

If you're not sure how many elements you need, don't worry about it because JavaScript is happy to let you add elements to and delete elements from the array as needed, and it will grow or shrink the array to compensate..

Next: One-Dimensional Array Example