Summary

In this lesson, you learned that:

  • An array stores several values, its elements, in one variable, in a fixed order: const names = ["Anna", "Tom"];. An empty array is [].
  • console.log(names) prints the array the way it is written in code: ["Anna", "Tom"]. To print it with a label, separate the label and the array with a comma: console.log("Names:", names). With +, the array would turn into the text Anna,Tom.
  • Each element has an index, counted from 0. names[0] reads the first element, names[1] = "Lucy"; changes the second one. An index with no element gives undefined.
  • The elements of an array created with const can change; you just can't store a different array in the variable.
  • The length property is the number of elements, and names[names.length - 1] is the last element.
  • A method is a command that belongs to a value, written after a dot. push() adds an element to the end of an array, pop() removes the last element and returns it, includes() returns true or false depending on whether the array contains a value, and indexOf() returns the index of a value, or -1 if it isn't there.
  • An array can contain other arrays, called nested arrays: groups[1][0] is the first element of the second inner array.
  • A text isn't an array, but you can read its characters by index (name[0]) and get its length. You can't change its characters; methods such as toUpperCase() return a new text instead.

In the next lesson, on loops, you'll learn to repeat code, for example to go through all the elements of an array one by one, however many there are. But first, practice what you know on a shopping list.

Instructions

Write an if statement: if shoppingList doesn't include item yet, add item to the end of shoppingList with push(). (Remember that ! turns true into false and back.)

After the if statement, print the list with a label, so that the console shows Shopping list: ["milk", "bread", "butter"]. (Once this step passes, you can try changing item to "bread": bread is already on the list, so it won't be added again.)

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

11/11

Next