Welcome to the Arrays course. Before any code, let's answer the most important question: why do arrays exist at all? Once you see the problem they solve, everything else in this course will make sense.
Imagine you're writing a program for a teacher. There are five students, and you need to store their marks and print the class average. With plain variables, it looks like this:
let mark1 = 72;let mark2 = 85;let mark3 = 64;let mark4 = 91;let mark5 = 58; const average = (mark1 + mark2 + mark3 + mark4 + mark5) / 5;That works for five students. Now the school has 500. You'd need 500 variables, a 500-term sum, and a new line of code every time a student joins. You can't even write a loop, because there's no way to say "the next variable" — mark1 and mark2 are just unrelated names to the computer.
An array is a single named container that holds many values in order, one after another. Each value sits in a numbered slot, and the slot number is called its index. In almost every language the first index is 0, so marks[0] is 72 and marks[4] is 58.
Now the teacher's program no longer cares how many students there are:
const marks = [72, 85, 64, 91, 58]; // could be 5 or 5,000 values let total = 0;for (let i = 0; i < marks.length; i++) { total += marks[i];}console.log(total / marks.length); // 74Five students or five thousand, the code is the same four lines. That's the whole point.
Notice what they all share: the slots are the same kind, they are next to each other, and you reach any one of them directly by its number.
marks holds the whole class. You pass one thing around, not 500.marks[437] takes the same tiny amount of time as reading marks[0] — the computer calculates where slot 437 is instead of searching for it. You'll see exactly how in the next lesson; it's written O(1), "constant time".Arrays aren't magic. Their strength — values packed side by side in fixed slots — also creates their weaknesses:
ArrayList, C++'s vector) hide this by quietly moving everything to a bigger block when they fill up — you'll build one yourself at the end of this course.Much of this course is about getting around these weaknesses: clever orders of visiting, extra helper arrays, sorting first, or pairing an array with a hash map.
Almost everywhere. A string is an array of characters. An image is a 2D array of pixels. A spreadsheet, a music playlist, a leaderboard, the frames of a video — all arrays. Even other data structures — stacks, queues, heaps and hash tables — are usually built on top of an array. Learning arrays well pays off in every course that follows.
The rest of this chapter opens the box: how an array actually sits in your computer's memory, why that makes marks[i] so fast, and why inserting in the middle is slow. Then Using arrays in code shows the everyday syntax in four languages, and Solving problems with arrays teaches you when to reach for one.
Was this helpful?