Javascript: Understanding Arrays

Arrays are a fundamental part of any programming language. In this chapter, you discover what they are, how to use them, and what makes JavaScript arrays distinct from arrays in other programming languages. You work with arrays to create lists, order lists, and add and remove items from lists.

The earlier posts in this blog involve working with variables that are standalone pieces of data, such as: var myName = “Chris”, var firstNumber = “3”, and var how ManyTacos = 8. There are often times in programming (and in life) where you want to store related data under a single name.

For example, consider the following types of lists:
  • A list of your favorite artists
  • A program that selects and displays a different quote from a list of quotes each time its run
  • A holiday card mailing list
  • A list of your top music albums of the year
  • A list of all your family and friends' birthdays
  • A shopping list
  • A to-do list
  • A list of New Year’s resolutions

Using single-value variables , you would need to create and keep track of multiple variables in order to accomplish any of these tasks. Here is an example of a list created using single-value variables:

var artist1 = "Alphonse Mucha";
var artist2 = "Chiara Bautista";
var artist3 = "Claude Monet";
var artist4 = "Sandro Botticelli";
var artist5 = "Andy Warhol";
var artist6 = "Wassily Kadinski";
var artist7 = "Vincent Van Gough";
var artist8 = "Paul Klee";
var artist9 = "William Blake";
var artist10 = "Egon Schiele";
var artist11 = "Salvador Dali";
var artist12 = "Paul Cezanne";
var artist13 = "Diego Rivera";
var artist14 = "Pablo Picasso";


This approach could work in the short term, but you’d quickly run into difficulties. For example, what if you wanted to sort the list alphabetically and move artists into the correct variable names based on their position in the alphabetical sort? You’d need to first move Mucha out of the artist1 variable (maybe into a temporary holding variable) and then move Bautista into the artist1 variable. The artist2 spot would then be free for Blake, but don’t forget that Mucha is still in that temporary slot! Blake’s removal from artist9 frees that up for you to move someone else into the temporary variable, and so on. Creating a list in this way quickly becomes complicated and confusing.

Fortunately, JavaScript (and every other programming language we know of) supports the creation of variables containing multiple values, called arrays.

Arrays are a way to store groups of related data inside of a single variable. With arrays, you can create lists containing any mix of string values, numbers, Boolean values, objects, functions, any other type of data, and even other arrays!


No comments:

Post a Comment