What Are Arrays?

By: Dusty Arlia
Published on September 9, 2012
Last Updated on Friday, July 17, 2015 at 11:05 PM
Total Updates: 8

If you need to keep track of a group of related items when writing a program, it's a good idea to make use of arrays. The JavaScript Array object is a constructor for arrays, which are high-level, list-like objects. A great example of what to store in an array would be the filenames of your pictures you would use for a slideshow. This is an example of what your code might look like:

var slideshow_pictures = ['pic1.jpg', 'pic2.jpg', 'pic3.jpg', 'pic4.jpg', 'pic5.jpg'];

Arrays have the object data type. The great thing about arrays is that you can store multiple values (or elements) into one variable that you can reference by name (and you can reference each element in your array by using the array name and index number). If you think of a variable as a single box in memory, then an array is a box with compartments for each element (or value).

The Grocery List Analogy

Arrays work great for lists of items. You can think of arrays as grocery lists. Arrays allow you to put all your items into one variable, just like a grocery list is a single piece of paper. Can you imagine using a new piece of paper for each item on your grocery list?

To create an array, you must first declare the array's name and then include a list of comma-separated values to be stored in the array. Each value supplied represents one item on your list. If the items are string values, place them in quotes (single or double). Place all the items in between square brackets ([]). Here's how to create an array called groceryList:

var groceryList = ['oatmeal', 
                   'half and half'];

When you declare an array and assign it values like the example above, this is still considered a single statement. You can tell because there is only one semicolon (;) at the end.

To make your programs easier to read, use multiple lines for large arrays or arrays with long strings. Like this:

var teamNames = ['Chicago Bulls',
                 'Cleveland Cavaliers',
                 'Detroit Pistons',
                 'Washington Wizards',

The JavaScript interpreter will ignore the extra whitespace.

A single array can also hold values with different data types. For example:

var dustyArlia = ['Dusty Arlia', 'male', 27, true];

You can even store arrays and other objects as elements inside an array.

The square brackets tell the JavaScript interpreter that it's dealing with an array.

When reading other JavaScript resources, sometimes you will see the Array keyword being used like this:

var groceryList = new Array ('oatmeal', 'blueberries', 'bananas', 'walnuts', 'half and half');

You can do it this way, but it is less elegant. Professionals tend to use array literals like our first example, because it's easier to type, there's less code, and in general, this way is more elegant.

Here are some other array articles: