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 textAnna,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 givesundefined. - The elements of an array created with
constcan change; you just can't store a different array in the variable. - The
lengthproperty is the number of elements, andnames[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()returnstrueorfalsedepending on whether the array contains a value, andindexOf()returns the index of a value, or-1if 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 itslength. You can't change its characters; methods such astoUpperCase()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.)