Problem: JavaScript’s `.sort()` mutates the array. Solution: Use `.toSorted()` instead. It returns a new sorted array. —— 👋 Join 30,000+ SWEs learning JS, React, Node.js, and Software Architecture: https://thetshaped.dev/ ——— 💾 Save this for later. ♻ Repost to help others find it. ➕ Follow Petar Ivanov + turn on notifications. #javascript #softwareengineering #programming
Small detail but a big win for avoiding unintended side effects in real codebases
.toSorted() is a great addition
Petar Ivanov I saw this .sorted() method few months ago and using it since then. This is quite useful method.
When EcmaScript introduced this function and many other functions that start with toFunction , the question I asked is :Why they did not just upgrade the existing functions and pass a boolean parameter (ex:immutable:true) and update the logic of the same function? Then, I realized ( maybe ), they will introduce ambiguity and may break things or it would be bad DX, and this is why they created a new function.
Good update overall, but a couple of important nuances are missing. .toSorted() is a nice improvement because it avoids mutation, but: It’s not universally supported yet in all runtimes/environments It can introduce polyfill or compatibility considerations in older Node/browser targets Also, in real systems the bigger issue isn’t just mutation—it’s unexpected shared state mutation in references, especially when arrays are passed through multiple layers or cached. So the safer mental model is: .sort() → mutates original reference (risk in shared state) .toSorted() → safer by default, but check runtime support Defensive copy ([...arr].sort()) → still widely used and predictable Nice direction though—immutability-first APIs are where JS is clearly heading.
Good reminder. The immutable array methods from ES2023 (.toSorted(), .toReversed(), .toSpliced(), .with()) are a nice addition. Less accidental mutations, especially when working with state in frontend frameworks.
The real value is that you get a new array & it does not mutate the original whch could cause unforeseen problems in production
.sort() mutates the original array while .toSorted returns a new sorted array and keeps the original untouched
sort() changes the original array, while .toSorted() returns a new sorted array, leaving the original one as it is.
I’ve been burned by .sort() enough times to appreciate this. .toSorted() feels like the version you wanted all along.