Mental Model
Arrays let us store many items in order and find them quickly by position.
Analogy: Think of an egg carton holding eggs in fixed spots so you can grab any egg fast by its place.
[0] -> 5 -> [1] -> 3 -> [2] -> 8 -> [3] -> 2 -> null
[0] -> 5 -> [1] -> 3 -> [2] -> 8 -> [3] -> 2 -> null
[0] -> 5 -> [1] -> 3 -> [2] -> 8 -> [3] -> 2 -> null ↑
5 -> [1] -> 3 -> [2] -> 8 -> [3] -> 2 -> null ↑
5 -> 3 -> [2] -> 8 -> [3] -> 2 -> null ↑
[0] -> 5 -> [1] -> 3 -> [2] -> 8 -> [3] -> 2 -> null Accessed value at index 2: 8
class ArrayExample { constructor(items) { this.items = items; } accessAtIndex(index) { if (index < 0 || index >= this.items.length) { return null; // index out of bounds } return this.items[index]; // direct access by index } } const arr = new ArrayExample([5, 3, 8, 2]); const value = arr.accessAtIndex(2); console.log(arr.items.map((v, i) => `[${i}] -> ${v}`).join(' -> ') + ' -> null'); console.log(`Accessed value at index 2: ${value}`);
if (index < 0 || index >= this.items.length) {return this.items[index];if (index < 0 || index >= this.items.length) {
if (index < 0 || index >= this.items.length) {
const fruits = ['apple', 'banana', 'cherry']; console.log(fruits[1]);
const numbers = [1, 2, 3]; numbers.add(4);
Pass the test and this pattern moves unknown