Why do indexes start at zero?
Where the zero index came from, why it's handier than it seems, and why “not found” is -1.
socks[0]. Not the first — the zeroth! Every beginner trips over this. Can't programmers count? They can. They just count not "numbers" but "distances".An index isn't an element's ordinal number but its offset from the start of the array: how many elements you skip to reach it. The first element sits right at the start — nothing to skip, offset 0. The second — offset 1. That's how the C language counted half a century ago: element address = start address + offset × element size.
const socks = ["red", "blue", "green"];
console.log(socks[0]);
console.log(socks.length);
console.log(socks[socks.length - 1]);length - 1.And zero has pleasant consequences:
- a loop reads naturally:
for (let i = 0; i < arr.length; i++)— exactly length steps, no+ 1or- 1; slice(0, 3)takes exactly 3 elements: the end isn't included, and the piece's length isend − start;- the remainder gives indexes in a circle:
i % arr.lengthalways lands inside the array.
That last point isn't theory. At the Murr club the cats take turns guarding the bowl, and the rota has to be drawn up a week ahead. Three cats, seven days. The cat on duty is the day number modulo the number of cats: 0, 1, 2, and back to 0.
const cats = ["Byte", "Murka", "Barsik"];
for (let day = 0; day < 7; day++) {
console.log("Day " + day + ": on duty — " + cats[day % cats.length]);
}day % 3 is always 0, 1 or 2 — exactly the array's indexes. Counting from one, you'd have to write (day - 1) % 3 + 1.The flip side is `-1`. Since zero is taken by a real element, “not found” can't be zero. So indexOf returns -1: no array ever has that index. It isn't a JavaScript quirk — nearly every zero-indexed language agreed on it.
const shelf = ["red", "blue"];
console.log(shelf.indexOf("red"));
console.log(shelf.indexOf("green"));
if (shelf.indexOf("red")) {
console.log("there is a red one");
} else {
console.log("no red one?!");
}if (0) means “no”. The right way: shelf.includes("red") or indexOf(…) !== -1.Finally, walking backwards. The warehouse is cleared from the top shelf: start at length - 1 and keep going while the index isn't below zero. A while fits nicely — it simply spins as long as the condition holds. Both bounds, length - 1 and 0, have to be exact, or the loop either reads undefined or forgets the bottom shelf.
const shelves = ["socks", "mittens", "scarf"];
let i = shelves.length - 1;
while (i >= 0) {
console.log("Taking down shelf " + i + ": " + shelves[i]);
i--;
}i >= 0, not i > 0: shelf zero is a real shelf too.Myth or fact?
Decide whether the statement is true. Got it wrong? Try again; once you're right, Byte explains what's going on.