Arrays

The Course
•
6 min read

Warm-up from memory

Print the numbers 1 through 3 using a loop. Explain whether a goal of 30 is reached at exactly 30. Then move on to lists.

An array is an ordered list written with square brackets. minutes[0] is its first item: indices start at zero. minutes.length is the number of items, so the last valid index is length minus one. Reading an absent index gives undefined; it does not create a value for you.

Use for...of to visit the values directly. You do not need an index just to sum a list. This is different from the counting for loop you wrote yesterday; both are useful, but use the one that expresses your intent.

push(value) appends an item. A const array can still have its contents changed: const prevents assigning a different array to the variable, not editing the array itself. We will explore shared references later today.

Predict before running

How many items exist after push? What would happen if you read minutes[3] before pushing?

Predict, then run JavaScript
const minutes = [20, 30];

minutes.push(15);
console.log(minutes[0]);
console.log(minutes.length);

let total = 0;

for (const value of minutes) {
  total = total + value;
}

console.log(total);
Check your prediction
20
3
65

Trace each statement in order. If your prediction differed, describe the first place your mental model and the result diverged before trying again.

The loop variable in for (const value of minutes) receives one array item per pass. JavaScript supplies a fresh value for each pass; you are not trying to reassign one const yourself.

items.join(", ") turns the items into one string with a comma and space between them. For example, ["read", "write"].join(" / ") produces "read / write". join leaves the array unchanged and returns an empty string for an empty array.

Edit a list and take a slice

Arrays offer more than appending. An index assignment replaces one item. pop() removes the last item and returns it. slice(start, end) returns a new array covering start up to, but not including, end. Omitting end takes the rest.

items[-1] does not read the last array element in JavaScript. Use items[items.length - 1] or items.at(-1). An empty array has no last item, so reading it gives undefined. Avoid writing past the end by accident; doing so can create empty slots rather than meaningful records.

Edit a list and take a slice JavaScript
const tasks = ["read", "watch", "practise"];

tasks[1] = "write";

const removed = tasks.pop();
const firstTwo = tasks.slice(0, 2);

console.log(tasks.join(", "));
console.log(removed);
console.log(firstTwo.join(" / "));
console.log(tasks.at(-1));
Check your prediction
read, write
practise
read / write
write

The original now has two items. slice returns another array; pop changed the original. Check both the returned value and the remaining array when learning a method.

Build a new list with a loop

A common transformation starts with an empty result, visits each input, and pushes one new value. Keep the input unchanged when the caller might still need it. We will later express this pattern with map, but the loop makes each step visible.

Modify this program to add a ten-minute break instead of doubling. Then predict the behavior for an empty input.

Build a new list with a loop JavaScript
const sessions = [10, 20, 30];
const doubled = [];

for (const minutes of sessions) {
  doubled.push(minutes * 2);
}

console.log(doubled.join(", "));
console.log(sessions.join(", "));
Check your prediction
20, 40, 60
10, 20, 30

We append into a different array. Reassigning the loop variable would not replace an element in the input array.

Distinguish a position from a value

An array index is a position starting at zero; the item stored there may be any value. The last valid position is length minus one. Looking beyond it gives undefined rather than an automatic error, so an accidental off-by-one can travel into a later calculation.

Use for-of when you need values and a numeric loop when you genuinely need positions. Avoid adding index bookkeeping to a simple total. Conversely, if the task asks which position matched, a value alone does not answer it. Choose the loop based on what the result must represent.

Positions and length JavaScript
const times = [10, 25, 40];

console.log(times.length);
console.log(times[0]);
console.log(times[times.length - 1]);
console.log(times[times.length]);
Check your prediction
3
10
40
undefined

There are three values but no index 3. Length counts elements; it is not itself a valid last index. This distinction also matters for an empty list, where no first value exists.

A total has an empty-list answer JavaScript
const times = [];
let total = 0;

for (const minutes of times) {
  total = total + minutes;
}

console.log(total);
times.push(15);
console.log(times.length);
console.log(times[0]);
Check your prediction
0
1
15

The accumulator works when no body runs. Pushing changes the array, not the const binding: the name still refers to the same list. This is different from assigning the name to another array.

Try the rule on new inputs

Create a list with one value and inspect positions 0 and 1. Then calculate a total with for-of and a count with length. Explain why initializing a total from the first element complicates the empty case.

Your turn

Exercise

Arrays: practise

Count how many sessions in [10, 25, 40, 15] lasted at least 20 minutes. Print 2. Then try an empty array: it should print 0.

Your working space JavaScript
const sessions = [10, 25, 40, 15];
let count = 0;
// Visit each value and count qualifying sessions.
Hint 1: the idea

The count starts outside the loop. Only some items increase it.

Hint 2: a first step

Inside for…of, use if (minutes >= 20) before adding one.

Show one solution
const sessions = [10, 25, 40, 15];
let count = 0;

for (const minutes of sessions) {
  if (minutes >= 20) {
    count = count + 1;
  }
}

console.log(count);
2

An empty list makes zero passes, so the initialized count of zero is already the correct answer. No special empty-list branch is needed.

What you should be able to explain

  • Which of push, pop, and slice change the array?
  • Why is the last index one less than length?
  • Build a new array containing only durations above 20 without modifying the original.

Was this article helpful?

Your response is saved on this device.