Learning object 17 of 100
Array indexing visualizer
See every element of an array with its index, counted from the start and from the end, and check what an index expression reads.
Loading…
What it shows
Indexes start at 0, so the last element is at length - 1. Reading an index that does not exist gives undefined rather than an error. Square brackets never count from the end: arr[-1] is undefined. Use arr.at(-1) for the last element.
Guided experiment
- Pick index
-1. Why do arr[-1] and arr.at(-1) differ? - Pick
arr.length. What does that read, and why? - Add a fifth element and check the last index again.
Predict
For const a = ["x", "y", "z"], what is a[a.length - 1]?
Related
Lessons: Lesson 26: Creating and accessing arrays
Projects: Project 9: Shopping Cart Price Calculator
Source: web/assets/js/objects/object-017.js in the companion repository.