Arrays
An array keeps many values in order under one name. In ["red", "green", "blue"], "red" sits at index 0 and the length is 3.
A list in one variable
Suppose a program tracks the scores of a whole class. Thirty variables named score1, score2, score3 would be miserable to work with, and impossible to loop over. An array is a single value that holds an ordered list of other values. You write it with square brackets and commas:
const fruits = ["apple", "banana", "cherry"];
console.log(fruits.length); // 3
console.log(fruits[0]); // apple
console.log(fruits[2]); // cherryEach value in an array is an element. Elements are numbered by index, starting at 0, exactly as characters in a string are. So the first element is fruits[0] and the last is fruits[fruits.length - 1]. Asking for an index that does not exist, such as fruits[10], does not cause an error; it gives undefined. An array can hold any kind of value, and the elements do not even have to be the same type, though in practice they usually are.
Changing an array
Unlike strings, arrays can be changed in place. Assign to an index to replace an element: fruits[1] = "blueberry". The method push adds an element to the end and pop removes the last one and gives it back. unshift and shift do the same at the start. This works even when the array was declared with const. const only stops the name from pointing to a different array; it does not freeze the contents.
const list = ["milk", "eggs"];
list.push("bread");
console.log(list.length); // 3
const last = list.pop();
console.log(last); // bread
console.log(list.join(", ")); // milk, eggsTwo more methods answer questions. includes(x) gives true if x is in the array, and indexOf(x) gives its index, or -1 if it is missing. join(", ") glues all the elements into one string with the given separator between them, which is the easiest way to print a list neatly.
Looping over an array
Arrays and loops belong together. A for loop with an index from 0 up to, but not including, the length visits every element. The for...of loop is shorter when you only need the values, not their positions:
const scores = [70, 85, 90, 55];
for (let i = 0; i < scores.length; i++) {
console.log(i, scores[i]);
}
let total = 0;
for (const s of scores) {
total += s;
}
console.log(total / scores.length); // 75Notice the condition i < scores.length, with < and not <=. With four elements the indexes are 0 to 3, and using <= would read one step past the end. This off-by-one mistake is one of the most common bugs in all of programming.
Two names, one array
Numbers and strings are copied when you assign them to another variable, but arrays are not. After const a = [1, 2]; const b = a; both names point to the very same array, so b.push(3) also changes what you see through a: a.length is now 3. If you need a separate copy, write const b = [...a];, which spreads the elements of a into a brand new array. Objects, covered in the next unit, behave the same way.
Worked example. Find the largest number in [4, 17, 9, 12] without Math.max. Start with let best = nums[0], loop over the rest, and whenever an element is bigger than best, store it in best. After the loop best is 17. The same shape, a variable that remembers the best so far, finds the longest word, the cheapest price or the earliest date.
| array | An ordered list of values in [ ] |
| element | One value inside an array |
| arr[0] | The first element |
| arr[arr.length - 1] | The last element |
| push / pop | Add to the end / remove from the end |
| includes | true if the value is in the array |
| join | Glue elements into one string |
| for...of | Loop over the values of an array |
| off-by-one | Going one step too far or too short, often <= instead of < |
- What does this print?
const a = [10, 20, 30]; console.log(a[1]); - What does this print?
const a = [10, 20, 30]; console.log(a.length); - What does this print?
const a = ["x", "y", "z"]; console.log(a[a.length - 1]); - What does this print?
const a = [1, 2]; a.push(3); a.push(4); console.log(a.length); - What does this print?
const a = [5, 6, 7]; const x = a.pop(); console.log(x, a.length);- 7 2
- 5 2
- 7 3
- What does this print?
const a = ["cat", "dog"]; console.log(a.indexOf("bird")); - What does this print?
const a = ["a", "b", "c"]; console.log(a.join("-")); - What does this print?
const a = [3, 4, 5]; let t = 0; for (const n of a) { t += n; } console.log(t); - What does this print?
const a = [1, 2, 3]; a[0] = 9; console.log(a[0] + a[2]); - What does this print?
const a = ["red", "green"]; console.log(typeof a[5]);- undefined
- An error
- string
- Which loop header visits every index of arr exactly once?
for (let i = 0; i < arr.length; i++)for (let i = 0; i <= arr.length; i++)for (let i = 1; i <= arr.length; i++)
- Arrays hold ordered values in [ ]; indexes start at 0.
- The last element is arr[arr.length - 1].
- push and pop add and remove at the end; const arrays can still change inside.
- includes, indexOf and join answer common questions.
- Loop with i from 0 while i < length, or use for...of for the values.