Spot the Array Index Bug
Find the Mistake Easy
Question
This code should print the last element but prints undefined. What is wrong?
Code
const arr = [1, 2, 3];
console.log(arr[arr.length]);
Hint
If length is 3, valid indices are 0, 1, 2 — not 3.
Explanation
arr.length is 3, but valid indices are 0, 1, 2. arr[3] is out of bounds and returns undefined. The fix is arr[arr.length - 1] which gives arr[2] = 3, the last element. This is a classic off-by-one error.
Related Resources
Related Lessons
- Arrays
Learn how arrays store ordered lists of values.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.