What Are Arrays?
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:
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
var groceryList = ['oatmeal', 'blueberries', 'bananas', 'walnuts', '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', ];
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.
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: