Creating and Accessing JavaScript Arrays

By Chris Minnick, Eva Holland

Creating an array in JavaScript starts the same way as any variable: with the var keyword. However, in order to let JavaScript know that the object you’re making isn’t just a normal variable, you put square brackets after it.

To create an array with nothing inside it, just use empty brackets, like this:

var favoriteFoods = [];

To create an array with data inside it, put values inside the brackets, separated by commas, like this:

var favoriteFoods = ["broccoli","eggplant",
"tacos","mushrooms"];

Storing different data types

Arrays can hold any of the different data types of JavaScript, including numbers, strings, Boolean values, and objects.

In fact, a single array can contain multiple different data types. For example, the following array definition creates an array containing a number, a string, and a Boolean value:

var myArray = [5, "Hi there", true];

Just as when you create regular variables, string values in arrays must be within either single or double quotes.

Getting array values

To get the value of an array element, use the name of the array, followed by square brackets containing the number of the element you want to retrieve. For example:

myArray[0]

Using an existing array definition, this will return the number 5.

Using variables inside arrays

You can also use variables within array definitions. For example, in the following code, you create two variables and then you use that variable inside an array definition:

var firstName = "Neil";
var middleName = "deGrasse"
var lastName = "Tyson";
var Scientist = [firstName, middleName, lastName];

Because variables are stand-ins for values, the result of these three statements is exactly the same as if you were to write the following statement:

var Scientist = ["Neil","deGrasse" "Tyson"];

To find out more about arrays, practice setting, retrieving, and changing array elements in the JavaScript Console.