Sub topic 2
Reading from the End with at()
This chapter assumes you know how to create an array, read elements with square brackets, and use the length property, all covered in the previous chapter. You should also be comfortable running snippets in Node.js or a browser console.
The problem with reading the last element
Square-bracket indexing counts from the front. To reach the last element, you have to work out its position from length:
const scores = [72, 88, 95, 61];
console.log(scores[scores.length - 1]); // 61
console.log(scores[scores.length - 2]); // 95This works, but it repeats the array name, and an off-by-one mistake is easy to make. It gets clumsier when the array comes from an expression, because you need a temporary variable just to read its length.
You might expect a negative index to count from the end, as it does in Python. In JavaScript it does not:
const scores = [72, 88, 95, 61];
console.log(scores[-1]); // undefinedSquare brackets turn -1 into the property name "-1". The array has no property with that name, so you get undefined. No error is thrown, which makes this bug easy to miss.
How at() works
at(index) returns the element at the given position. A non-negative index counts from the front. A negative index counts back from the end, so -1 is the last element.
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.at(0)); // 'apple'
console.log(fruits.at(-1)); // 'cherry'
console.log(fruits.at(-2)); // 'banana'
console.log(fruits.at(5)); // undefined
console.log(fruits.at(-4)); // undefinedFor a negative argument, at() adds it to length, so at(-1) on a three-element array reads index 2. If the result falls outside the range 0 to length - 1, at() returns undefined.
at() is especially handy on the result of an expression, where you don't have a variable to call length on:
const words = 'the quick brown fox'.split(' ');
console.log(words.at(-1)); // 'fox'
console.log('the quick brown fox'.split(' ').at(-2)); // 'brown'It also works on strings and typed arrays:
console.log('hello'.at(-1)); // 'o'
console.log(new Uint8Array([4, 8, 15]).at(-1)); // 15Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `arr[-1]` | Returns `undefined` silently | Use `arr.at(-1)` |
| `arr.at(-1) = value` | SyntaxError: invalid assignment target | Use `arr[arr.length - 1] = value` or `arr.with(-1, value)` |
| `arr.at(1.9)` | Reads index `1`, because the decimal part is dropped | Pass whole numbers |
| Treating `undefined` as "not found" | An element that really holds `undefined` looks the same | Check `length` when the difference matters |
Exercises
Exercise
Given const queue = ['a', 'b', 'c', 'd'];, what do queue.at(-3), queue[-3], and queue.at(-5) return?
Show answer
queue.at(-3) returns 'b' because 4 + (-3) = 1. queue[-3] returns undefined because it looks up a property named "-3". queue.at(-5) returns undefined because 4 + (-5) = -1, which is out of range.
Exercise
Write a function secondToLast(arr) that returns the second-to-last element, or undefined if the array has fewer than two elements. Do not use length.
Show answer
const secondToLast = arr => arr.at(-2); For a one-element array, 1 + (-2) = -1 is out of range, so at() already returns undefined. No extra check is needed.