Arrays
Indexes and length
An item's position in an array or a character's in a string (from zero), and how many there are.
Why it exists
An array is a numbered list, and the number (index) lets you grab the item you need right away: the first message, the last order, the third slide — without walking through all of them. length says how many items there are: "3 items in your cart", "showing 10 of 42", "password too short". Almost any code with lists relies on these two things.
Where it's used
- Counters in the interface: "Cart: 3", "Characters: 120/280".
- The first and last item:
messages[0],orders[orders.length - 1]. - Checking for empty:
if (items.length === 0)— show "Nothing here yet". - Walking by index in a for loop, and checking a password's length.
Syntax
array[index]
string[index]
array.lengthExamples
const colors = ["red", "green", "blue"];
colors[0]; // → "red"
colors.length; // → 3
colors[colors.length - 1]; // → "blue"
colors[3]; // → undefined
"cat"[1]; // → "a"const messages = ["Hi", "How are you?", "Bye"];
messages[messages.length - 1]; // → "Bye"
messages.at(-1); // → "Bye"const password = "qwerty";
password.length; // → 6
password.length >= 8; // → falseconst word = "cat";
word[0] = "C";
word; // → "cat" — a string can't be changed this way
const letters = ["c", "a", "t"];
letters[0] = "C";
letters; // → ["C", "a", "t"]Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
Indexes start at zero: the first item is [0], the second [1], the last [length - 1]. It's historical: an index is an "offset from the start", and the first item's offset is zero.
Accessing an index that doesn't exist doesn't throw an error — it quietly gives undefined. That's convenient, but it makes bugs easy to miss.
Strings have indexes and length too, but strings are immutable: text[0] = "C" changes nothing. Array indexes can be assigned.
An array's length is "last index + 1", and it updates automatically on push. Newer code can also use arr.at(-1) for the last item.
Traps
How it differs from…
for...ofloopWhen you don't need the number, for...of spares you indexes and off-by-one mistakes.
When to pick something else
Don't use indexes as record "identifiers": they shift after deleting or sorting. To refer to a specific order or user, keep its id.
Practice
Lessons where this appears
- Byte's sock empireTale · Chapter 5 · Arrays and loops
- Why do indexes start at zero?Why? · Chapter 5 · Arrays and loops
- The sock warehouseWorkshop · Chapter 5 · Arrays and loops
- Largest numberLab · Chapter 5 · Arrays and loops
- Trim a teaserLab · Chapter 6 · Strings
- Why is `...` both spread and rest?Why? · Chapter 9 · Destructuring, spread and rest