Lesson 1
Arrays & indexing
Build a practical mental model for arrays & indexing and use it in working JavaScript.
By the end, you will be able to…
- Explain arrays & indexing in your own words
- Use arrays & indexing in a small program
- Recognize and debug a common failure mode
Build the mental model
Arrays are ordered lists indexed from 0. The last element is always at index length - 1, a small formula that trips up nearly every beginner at least once.
Syntax and working example
Read the code from inputs to output. Predict what it prints, then run it and change one value.
Why this matters
Correct indexing underlies every list operation you'll write — pagination, carousels, 'show the last message' — get it wrong and you're off by one everywhere downstream.
Real-world example
A chat app showing the most recent message reads messages[messages.length - 1] using exactly this pattern.
Common mistakes
- Using fruits[fruits.length] and getting undefined (the valid last index is length - 1)
- Forgetting arrays are zero-indexed
- Mutating an array while assuming it copies automatically
Try it yourself
Challenge
Write getMiddle(array) that returns the middle element for an odd-length array.
Knowledge check
What index holds the last element of an array named list?
Summary
Arrays index from 0; the last item is always at array.length - 1.