Copy the array before you sort it
JavaScript’s sort() changes its input. Keep display ordering separate from shared data with a copied array and an explicit comparator.
This looks like a harmless way to show the cheapest products first:
const cheapestFirst = products.sort((a, b) => a.price - b.price);
But `sort()` changes `products` and returns that same array. You haven’t created a separate view—you’ve reordered the original data. That matters when another component, cache entry, or function holds a reference to it.
Copy the array before sorting:
const products = [
{ id: 'keyboard', price: 90 },
{ id: 'cable', price: 12 },
{ id: 'mouse', price: 45 },
];
const cheapestFirst = [...products].sort(
(a, b) => a.price - b.price,
);
console.log(cheapestFirst.map(product => product.id));
// ['cable', 'mouse', 'keyboard']
console.log(products.map(product => product.id));
// ['keyboard', 'cable', 'mouse']
console.log(cheapestFirst === products);
// false
Paste that into a JavaScript console. Then remove `[...products]` and use `products.sort(...)`. Both lists will print in price order, and the identity check will become `true`.
The distinction that makes this click: **sorting is an ordering operation, but `sort()` is also a write operation.** Copying gives that write its own array.
Keep the comparator explicit
Without a comparator, JavaScript sorts elements by their string representations. That’s documented behavior, which is why `[12, 90, 100].sort()` produces `[100, 12, 90]`.
For finite numeric prices, `a.price - b.price` gives ascending order. Swap the operands for descending order. If prices can be missing or invalid, decide where those entries belong before relying on subtraction.
The copy is shallow
The new array still contains the same product objects:
cheapestFirst[0].price = 0;
console.log(products.find(product => product.id === 'cable').price);
// 0
Copying protects the original array’s order; it doesn’t isolate edits to its contents.
My default for display sorting is to copy first. The tradeoff is an extra array allocation. If a function owns a temporary array and nothing else needs its original order, sorting that array directly is a reasonable choice.