What Is an Array?

Accessing and modifying array items

Items in an array are numbered, starting from zero. This number is called the item's index. So the first item has index 0, the second has index 1, and so on. You can access individual items in the array using bracket notation and supplying the item's index, in the same way that you accessed the letters in a string.
  1. Enter the following into your console:
  2. const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
    console.log(shopping[0]);
    // returns "bread"
  3. You can also modify an item in an array by giving a single array item a new value. Try this:
  4. const shopping = ["bread", "milk", "cheese", "hummus", "noodles"];
    shopping[0] = "tahini";
    console.log(shopping);
    // shopping will now return [ "tahini", "milk", "cheese", "hummus", "noodles" ]

    Note: We've said it before, but just as a reminder - computers start counting from 0!

  5. Note that an array inside an array is called a multidimensional array. You can access an item inside an array that is itself inside another array by chaining two sets of square brackets together. For example, to access one of the items inside the array that is the third item inside the random array (see previous section), we could do something like this:

  6. const random = ["tree", 795, [0, 1, 2]];
    random[2][2];
  7. Try making some more modifications to your array examples before moving on. Play around a bit, and see what works and what doesn't.