Reading Items (and Why We Count From Zero)

Grade 7, page 2 of 14. A two-minute read.

To get an item out of an array, write the array's name followed by the item's index in square brackets. And just like the characters in a string (Grade 2), indexes start at 0:

JavaScript
const foods = ["burger", "omelet", "pancakes", "soup"];

console.log(foods[0]);
console.log(foods[1]);
console.log(foods[3]);

It prints

burger
omelet
soup

The first item is at index 0. The second is at index 1. The fourth (and last) item is at index 3.

Okay, it's time. Let's finally talk about this zero business.

Professor’s CornerWhy does counting start at zero?

Think of the index not as "which number item is this?" but as "how many steps from the start?" The first carriage is right at the front of the train, so it's 0 steps from the start. The second carriage is 1 step from the start. The third is 2 steps away. That's why the index of the first item is 0. Under the hood, the computer finds an item by starting at the beginning of the array in memory and jumping forward "index" spaces. Jumping forward 0 spaces lands you on the first item. It's not that programmers enjoy being confusing. It's just how the math works out.

And now, as promised in Orientation, the explanation for Grade 13: Professor Semicolon insists that if you count Kindergarten as "Grade 0," then the grades all make perfect sense. We've checked his math three times and it still doesn't add up. The truth? We just had too much cool stuff to teach. 🤷

What if the index doesn't exist?

JavaScript
const foods = ["burger", "omelet", "pancakes", "soup"];
console.log(foods[10]);
console.log(foods[-1]);

It prints

undefined
undefined

No error. JavaScript just shrugs and gives you undefined, because there's no carriage at that position. (This quiet behavior is how a lot of off-by-one bugs sneak in unnoticed!)

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning