Arrays & Zero-Based Indexing
Quick Overview
Arrays index from 0, so the last element sits at `length - 1` and `arr[arr.length]` is always `undefined`. Nearly every off-by-one bug lives at that one boundary.
Deep Dive
1. Ordered Lists of Data
An array is an ordered list of values enclosed in square brackets [...]. Array elements can hold any data type, numbers, strings, objects, or even nested arrays.
2. Why It Matters
Arrays store sequences of data (user lists, product catalogs, order items) accessible by 0-based numerical index positions.
3. Zero-Based Indexing & Length
Array positions start at index 0 (first item = arr[0]). You can find the last item using arr[arr.length - 1] or modern arr.at(-1):
const fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // "Apple" (First element)
console.log(fruits[1]); // "Banana" (Second element)
console.log(fruits.length); // 3
console.log(fruits.at(-1)); // "Cherry" (Last element)
// Modifying array contents
fruits.push("Dragonfruit"); // Add item to end
console.log(fruits.length); // 4
4. Core Array Mutating Methods
push(item): Add to end of array.pop(): Remove item from end of array.unshift(item): Add item to start of array.shift(): Remove item from start of array.
const stack = [10, 20];
stack.push(30); // [10, 20, 30]
stack.pop(); // Returns 30 -> [10, 20]
5. Common Mistakes
- Out-of-Bounds Access: Reading an index that does not exist (like
fruits[99]) returnsundefinedrather than throwing an error. Always check.lengthor verify array bounds. - Confusing Array Length with Last Index: An array with
length = 5has valid indices from0to4. Accessingarr[5]returnsundefined!
6. Try It Yourself
Write it yourself. The tests below run against your code.
Get Last Item of Array
Examples
7. Next Steps
Arrays store ordered lists. Next, let's explore Objects for key-value records!
Next Up in JavaScript Engine & Core Language
Data Types in JavaScript: Primitives vs. Objects
Primitives copy by value and objects copy by reference, so `b = a` duplicates a number but shares an object. That single distinction explains most surprise mutations in a codebase.
Variables: const, let & var (The Box Metaphor)
`const` prevents reassignment, not mutation: a `const` object's properties can still be changed. `let` is scoped to its block, while `var` is function-scoped and leaks out of loops.
Strings & Template Literals `${}`
Only backticks interpolate: `${user}` reads the variable, while the identical text in quotes prints literally. Strings are immutable, so every method returns a new one rather than editing in place.