What Is an Array?

An array is a way to store a collection of multiple items under a single variable name. This section introduces how to create, delete and access array elements.  Think about the following as you read the article:

  • How are array elements accessed?
  • What methods are used to access the elements of an array?
  • How would you convert a string into an array?


Creating arrays

Arrays consist of square brackets and items that are separated by commas.

  1. Suppose we want to store a shopping list in an array. Paste the following code into the console:
  2. const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
    console.log(shopping);
  3. In the above example, each item is a string, but in an array we can store various data types - strings, numbers, objects, and even other arrays. We can also mix data types in a single array - we do not have to limit ourselves to storing only numbers in one array, and in another only strings. For example:

    const sequence = [1, 1, 2, 3, 5, 8, 13];
    const random = ["tree", 795, [0, 1, 2]];
  4. Before proceeding, create a few example arrays.