JavaScript Intermediate Language Basics · 6 min read

Array at, findLast, and toSorted

Lesson 34 of 38 in the JavaScript learning path.

How do I read the last item and sort a copy of an array?

at accepts a negative index. toSorted and toReversed return a new array.

sort mutates. A shared lesson list that gets sorted in a widget surprises the next reader.

Syntax & Parameters

Syntax
lessons.at(-1); lessons.toSorted((a, b) => a.title.localeCompare(b.title));

Example

Interactive preview available
sort.js
const lessons = [
  { title: "Queries" },
  { title: "Blade" },
  { title: "Routes" }
];
const last = lessons.at(-1);
const sorted = lessons.toSorted((a, b) => a.title.localeCompare(b.title));
const label = document.querySelector("#out");
label.textContent = [
  "last " + last.title,
  "sorted " + sorted.map((item) => item.title).join(", "),
  "original " + lessons.map((item) => item.title).join(", ")
].join(" | ");

Expected Output

last Routes | sorted Blade, Queries, Routes | original Queries, Blade, Routes

Line-by-Line Walkthrough

  1. at(-1) reads the last item without length - 1.
  2. toSorted compares titles with localeCompare.
  3. The original array stays in insertion order.
  4. The label shows last, sorted, and original.
  5. findLast would return the last match of a test.
  6. sort would have rewritten lessons.
  7. localeCompare handles accents better than >.
  8. An empty array makes at return undefined. Check it.

Common Pitfalls & Security

Read the limits before you copy this.

  • toSorted is a copy. Forgetting to use the return value looks like nothing happened.
  • sort still mutates if you call it by habit.
  • localeCompare without a locale uses the runtime default.
  • at on an empty array is undefined, not an error.

Best Practices & Modern Standards

Use at for ends of arrays and toSorted when the source must stay put.

Pass an explicit compare. The default sort is lexicographic and will mis-order numbers.

Real-World Use

A sidebar shows the latest lesson with at(-1) and a sorted copy for the A to Z menu, leaving the homepage order alone.

Frequently Asked Questions

Does toSorted change the original?

No. It returns a new array.

What does at(-1) mean?

The last element. -2 is the one before that.

What about old browsers?

A current evergreen set has these methods. A length check is the fallback.

How do I sort numbers?

Pass (a, b) => a - b. The default sort compares as strings.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…