Zero-Based Indexing
You'll learn how JavaScript arrays number their positions starting from 0, and how to access elements by their index.
What Is Zero-Based Indexing?
In JavaScript, arrays use zero-based indexing, which means the first element is at position 0, not position 1. The second element is at position 1, the third at position 2, and so on. This might feel counterintuitive at first, but it's a fundamental convention in JavaScript (and many other programming languages).
Think of it like floor numbers in some European buildings: the ground floor is 0, the first floor above ground is 1, and so forth.
Accessing Elements by Index
You access array elements using square brackets [] with the index number:
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits[0]); // 'apple' (first element)
console.log(fruits[1]); // 'banana' (second element)
console.log(fruits[2]); // 'cherry' (third element)
The index represents the offset from the beginning of the array. The first element has zero offset, so it's at index 0.
Why Zero-Based?
Zero-based indexing reflects how memory works internally: the index tells the computer how many positions to move from the array's starting point. Zero steps means you're at the start.
Common Mistake
The last element is at index length - 1, not length:
const colors = ['red', 'green', 'blue'];
console.log(colors[3]); // undefined (no fourth element!)
console.log(colors[2]); // 'blue' (last element)
Key Takeaway: JavaScript arrays start counting at index 0, so the first element is array[0], and the last element is array[array.length - 1].