9 / 12 · Intro
Arrays in JavaScript
An array keeps many values in order under one name. In ["red", "green", "blue"], "red" sits at index 0 and the length is 3.
Jump to the 11 practice questionsYou will learn
- Keep values in order in an array and reach them by index
- Loop over an array and see when two names share one array
Before this: Loops: for and while
1Explain
A list in one variable
Each 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.
const fruits = ["apple", "banana", "cherry"];
console.log(fruits.length); // 3
console.log(fruits[0]); // apple
console.log(fruits[2]); // cherry3
apple
cherry2Explore
Pick an index
Indexes run from 0 to length - 1. Outside that range JavaScript gives undefined instead of an error.
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]);apple3Problem
The last element
const a = ["x", "y", "z"];
console.log(a[a.length - 1]);Hint
length is 3, so the last index is 2.
Solution
Answer: z
length - 1 is 2, the last index.
4Explain
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.
The array is drawn as a row of boxes. push adds a box at the end, pop takes the last one off and hands it back.
const list = ["milk", "eggs"];list.push("bread");console.log(list.length); // 3const last = list.pop();console.log(last); // breadconsole.log(list.join(", ")); // milk, eggs
3 bread milk, eggs
5Problem
pop and length
What does this print?
const a = [5, 6, 7];
const x = a.pop();
console.log(x, a.length);Hint
pop returns the element it removes.
Solution
Answer: 7 2
pop removes and returns the last element, 7, leaving 2 elements.
6Explain
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:
First i walks the indexes 0 to 3, then for...of hands over each value in turn.
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); // 75
0 70 1 85 2 90 3 55 75
7Problem
Add the values
What does this print?
const a = [3, 4, 5];
let t = 0;
for (const n of a) {
t += n;
}
console.log(t);Hint
for...of gives 3, then 4, then 5.
Solution
Answer: 12
3 + 4 + 5 = 12.
8Explain
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.
A dashed outline means "the same array as above". [...a] makes a new array of its own.
const a = [1, 2];const b = a;b.push(3);console.log(a);const c = [...a];c.push(4);console.log(a, c);
[1,2,3] [1,2,3] [1,2,3,4]
9Problem
An index that is not there
What does this print?
const a = ["red", "green"];
console.log(typeof a[5]);Hint
Reading past the end does not stop the program.
Solution
Answer: undefined
Reading a missing index gives undefined, not an error, so its type is "undefined".
10Practice
First, last, length
Print the first element, then the last element (using length), then the length, one per line.
apple
cherry
3const fruits = ["apple", "banana", "cherry"];
console.log(fruits[1]);
Hint
The last element is at fruits.length - 1, not fruits.length.
A solution
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]);
console.log(fruits[fruits.length - 1]);
console.log(fruits.length);11Practice
push and join
Add "kiwi" to the end of the array with push, then print apple, banana, cherry, kiwi.
apple, banana, cherry, kiwiconst fruits = ["apple", "banana", "cherry"];
// Add "kiwi" to the end, then print
// the list joined with ", ".
console.log(fruits.join(" "));
Hint
push("kiwi") first, then join with a comma and a space: ", ".
A solution
const fruits = ["apple", "banana", "cherry"];
fruits.push("kiwi");
console.log(fruits.join(", "));12Explain
Common mistakes
const list = ["milk", "eggs"];
list.push("bread");
list = ["rice"];TypeError: Assignment to constant variable. (line 3)
- The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
- After the colon: what went wrong, usually with the name involved.
- The line number shows where the program stopped. A SyntaxError stops it before any line runs.
A const array can change inside (push works), but the name cannot be pointed at a new array.
const names = ["Ana", "Ji"];
console.log(names[2].toUpperCase());TypeError: Cannot read properties of undefined (reading 'toUpperCase') (line 2)
- The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
- After the colon: what went wrong, usually with the name involved.
- The line number shows where the program stopped. A SyntaxError stops it before any line runs.
names[2] does not exist, so it is undefined, and undefined has no methods. Check the index first.
13
Summary
- 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.