Home

What Are JavaScript Arrays?

|
|  Updated:  
2016-03-26 07:26:22
JavaScript Essentials For Dummies
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 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.