# Arrays

### Array Basics

Arrays are variables that can hold a list of values. This is very useful if you have a bunch of the same type of something (e.g.: people's names, image file names, color values, booleans, objects, etc). There are a couple different ways that we can declare and define arrays. Here are two ways to create empty arrays:

```var arrayName = new Array();
var arrayName = [];```

We can also define a new array with some initial values. Here are some arrays with three initial string values:

```var arrayName = new Array("first thing", "second thing", "third thing");
var arrayName = ["first thing", "second thing", "third thing"];```

Here are some numeric values:

```var arrayName = new Array(4, 8, 15, 16, 23, 42);
var arrayName = [4, 8, 15, 16, 23, 42];```

Here are some boolean values:

```var arrayName = new Array(true, false, true, true, false);
var arrayName = [true, false, true, true, false];```

Writing to arrays is fairly straight forward. All arrays have indexes that are the numeric address where the value is stored in the array. These arrays are always in sequential order, and always begin at 0. We can assign values to these indexes manually by referring directly to the number of the index using the square bracket syntax.

```arrayName = "first thing";
arrayName = "second thing";
arrayName = "third thing";```

We can read the number of elements being stored in an array by using the length property.

`console.log(arrayName.length);`

### Parallel Arrays

We can store multiple properties that are associated with each other across different arrays. We keep these properties associated by making sure they use the same number index across the different arrays. There's nothing to maintain their alignment other than your manual entry of the values to the arrays.

```var firstName = [];
var lastName = [];
var email = [];

firstname = "Aaron";
lastname = "Siegel";
email = "aaronsie@usc.edu";

firstname = "Steve";
lastname = "Child";
email = "child@usc.edu";

firstname = "Patrick";
lastname = "Dent";
email = "dent@usc.edu";```

### Dynamic Page Content Using Arrays

We can store a bunch of different properties and dynamically access them from an array. In the example below we will store a an array of image file names and then use the Math.random() function to generate a number within a specific range in order to retrieve an image file name.

```var images = ["la1.jpg", "la2.jpg", "la3.jpg", "la4.jpg"];
var caption = ["Downtown skyline.", "Hollywood reservoir.", "USC campus.", "Memorial colosseum."];
var num = Math.floor(Math.random()*4);
var imgName = images[num];
var cap = caption[num];
document.write("<img src='" + imgName + "' alt='" + cap + "'><br>" + cap);```