Course content

Module 1

Module 2

Module 3

Module 4

Module 5

Module 6

Module 7

Module 8

Module 9

Module 10

Module 11

Module 12

Module 13

Module 14

Module 15

Module 16

Module 17

Module 18

25 min

Representing Collections with Arrays

Model an ordered collection

By the end of this lesson

  • Model an ordered collection
  • Distinguish index from length

One value is no longer enough

A report receives three order totals: 20, 35 and 15. Separate names such as total1 and total2 do not scale when another order arrives. An array stores an ordered sequence under one name.

const totals = [20, 35, 15];
console.assert(totals.length === 3);
console.assert(totals[0] === 20);
console.assert(totals[totals.length - 1] === 15);
console.assert(totals[3] === undefined);

Square brackets create an array and access an element by index. Indices start at zero. Length counts elements, so the last index of this nonempty array is length minus one. Access outside the existing positions yields undefined, not an automatic error.

For the exercises, use dense arrays: consecutive positions without gaps. Avoid assigning directly to an arbitrary distant index. It creates missing positions and complicates iteration.

Guided review

A loop using index <= length attempts one extra access. With numeric calculations, that undefined value can lead to NaN. Use index < length when visiting every element by index.

An empty array [] is a real collection with length zero, not null. It is truthy; test its length to ask whether it contains entries.

Independent exercise

Represent four daily counts: 2, 0, 4 and 1. Read the third count and explain the difference between a count of zero and a missing fifth entry. Predict the length after adding a fifth actual value later.

Correction

Use [2, 0, 4, 1]. Index 2 gives 4. Zero is a supplied count; index 4 currently yields undefined. With a fifth entry the length becomes 5. A report must not silently interpret missing information as a measured zero.

Review

Choose arrays when order and a collection of entries matter. The data should have a consistent meaning: mixed unrelated values make later operations harder to explain.

Lesson complete?

Your progress is saved on this device.