JavaScript For Kids For Dummies
Book image
Explore Book Buy On Amazon

Arrays are a special kind of variable in JavaScript that can hold multiple values using the same name. You can picture an array as being similar to a dresser with multiple drawers. Each drawer can hold something different, but the whole thing is still your dresser.

If you want to tell someone which drawer to look in for socks, you can say, "The socks are in the top drawer." If they're in the next drawer down, you'd say, "They're in the second drawer from the top." If you were to make a list showing what's in each drawer of your dresser, you would do something like this:

Top drawer: Socks
Second drawer: Shirts
Third drawer: Pants

If you understand how your dresser organizes your clothes, you have a good start on understanding how JavaScript arrays organize data.

If you wanted to create a JavaScript array to describe the contents of the dresser, you could use the following code:

var dresser = ["socks","shirts","pants"];

This statement creates three "drawers" (or elements, as they're called in JavaScript). When you want to know what's in each of the elements, you can simply ask JavaScript. For example, to find out what's in the third element, you use the following:

dresser[2]

The value of dresser[2] is pants.

JavaScript starts counting from zero. So, the first element of an array is number 0, the second is 1, and the third is 2.

The maximum number of elements that a JavaScript array can hold is 4.29 billion. So, pretty much anything that you want to list will fit into an array!

About This Article

This article is from the book:

About the book authors:

Chris Minnick and Eva Holland are experienced web developers, tech trainers, and coauthors of Coding with JavaScript For Dummies. Together they founded WatzThis?, a company focused on training and course development.

This article can be found in the category: