Reference · module 4
Arrays and loops
Everything this module explains, on one page.
Arrays
Keep many values in one list and reach any of them by position.
- const fruits = ["apple", "pear", "plum"]; is an array: an ordered list of values in square brackets, separated by commas. It can hold numbers, strings, or both.
- Items are numbered from zero: fruits[0] is "apple" and fruits[2] is "plum". Asking for an index that does not exist, like fruits[3], gives undefined rather than an error.
- fruits.length is the number of items, here 3. So the last item is always fruits[fruits.length - 1], and fruits.at(-1) is a shorter way to say the same.
The mistake you are about to make
fruits[fruits.length]
fruits[fruits.length - 1]
In a three-item array the third item feels like fruits[3]. Counting starts at zero: indexes are 0, 1 and 2, and fruits[3] quietly returns undefined without any error.
Loops
Repeat work for every item, or while a condition holds.
- for (const fruit of fruits) { ... } runs the body once per item, with fruit holding the current item. It is the simplest way to walk through an array from start to end.
- for (let i = 0; i < 3; i++) { ... } counts: start at 0, repeat while i < 3, add one after each pass. The body runs for i = 0, 1 and 2, three times in total.
- while (condition) { ... } repeats as long as the condition stays true. Something inside must eventually make it false, or the loop never ends and the page freezes.
The mistake you are about to make
for (const n in [10, 20, 30])
for (const n of [10, 20, 30])
in and of sound nearly the same, and both run without errors. in walks the indexes, as strings: "0", "1", "2". Only of gives you the values.
Changing arrays
Add, remove and look for items.
- push adds an item to the end: list.push("milk"). pop removes the last item and returns it. Both change the array itself rather than making a new one.
- includes asks whether a value is in the array: [1, 2, 3].includes(2) is true. indexOf gives its position instead, or -1 when the value is missing.
- const list = []; list.push(1); works, even though list is const. const stops you pointing the name at another array; it does not freeze the array it already points at.
The mistake you are about to make
if (list.indexOf(item)) {
if (list.includes(item)) {
indexOf sounds like a presence check. It returns a position: 0 for the first item, which is falsy, and -1 for a missing one, which is truthy. The condition comes out backwards.