Home

Creating and Accessing JavaScript Arrays

|
Updated:  
2016-03-26 07:26:36
|
JavaScript Essentials For Dummies
Explore Book
Buy On Amazon

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",<br/>"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.

About This Article

This article is from the book: 

About the book author:

Chris Minnick is an accomplished author, teacher, and programmer. Minnick authored or co-authored over 20 books, including titles in the For Dummies series. He has developed video courses for top online training platforms and he teaches programming and machine learning to professional developers at some of the largest global companies.

Eva Holland is an experienced web developer, tech trainer, and coauthor of Coding with JavaScript For Dummies. She is a co-founder of WatzThis?, a company focused on training and course development.