Albert Em’s Post

.sort() has been lying to you for 25 years It doesn't return a sorted array. It returns YOUR array. Mutated. Original gone. Every React dev has learned this the hard way: const [items, setItems] = useState([3, 1, 4]) setItems(items.sort()) // Bug: mutates state directly We've all been doing the spread workaround: const sorted = [...items].sort() Ugly. Easy to forget. JavaScript finally fixed it: Four new immutable array methods: → toSorted() - sort without mutating → toReversed() - reverse without mutating → toSpliced() - splice without mutating → with(index, value) - replace item without mutating Works exactly like the originals. Returns a new array. Original stays untouched. Perfect for React state. Perfect for Redux reducers. Perfect for anywhere mutation causes bugs. Available in all browsers since mid-2023. Node 20+. No more spread operator workarounds. No more accidental mutations. No more "wait why did my list change". Use the immutable versions. #javascript #frontend #webdev #programming #webdevelopment #react #typescript #cleancode #devtips #arrays

  • No alternative text description for this image

Why did you decide to share a method which appeared 3 years ago? Moreover clarifying “finally fixed”.

Nice post, Albert. Devs often forget the immutability in JavaScript. I’ve written a detailed blog couple years ago on how to sort arrays in JavaScript. Shamelessly sharing the link here https://www.hassib.co/blog/how-to-sort-arrays-in-javascript

another breaking news on linkedin

toSorted() honestly feels like one of those small JS updates that quietly saves you from so many subtle React bugs. anything that reduces accidental mutation is a win.

See more comments

To view or add a comment, sign in

Explore content categories