Sort vs toSorted in JavaScript: Key Differences and Usage
sort() changes the original array by sorting it in place, while toSorted() returns a new sorted array without modifying the original. Use toSorted() when you want to keep the original array unchanged and sort() when you want to sort directly.Quick Comparison
Here is a quick side-by-side comparison of sort() and toSorted() methods in JavaScript.
| Feature | sort() | toSorted() |
|---|---|---|
| Mutates original array? | Yes, it sorts the array in place. | No, returns a new sorted array. |
| Return value | The sorted original array. | A new sorted array copy. |
| Introduced in | Since early JavaScript versions. | ECMAScript 2023 (ES14). |
| Usage | Use when you want to change the original array. | Use when you want to keep original array intact. |
| Performance | Slightly faster due to no copying. | May be slower due to creating a new array. |
| Chainable | Yes, returns the original array. | Yes, returns a new array. |
Key Differences
The main difference between sort() and toSorted() lies in whether they change the original array. sort() sorts the array you call it on, changing its order permanently. This means if you need the original order later, you must copy the array before sorting.
On the other hand, toSorted() is a newer method introduced in ECMAScript 2023 that returns a new array sorted according to the same rules but leaves the original array untouched. This helps avoid bugs caused by accidental mutation and makes code easier to reason about.
Both methods accept the same optional comparison function to customize sorting order. However, because toSorted() creates a new array, it may use more memory and be slightly slower, but it improves safety and clarity in your code.
Code Comparison
Here is how you use sort() to sort an array of numbers in ascending order.
const numbers = [5, 3, 8, 1]; numbers.sort((a, b) => a - b); console.log(numbers);
toSorted Equivalent
Here is the equivalent code using toSorted() which does not change the original array.
const numbers = [5, 3, 8, 1]; const sortedNumbers = numbers.toSorted((a, b) => a - b); console.log(sortedNumbers); console.log(numbers);
When to Use Which
Choose sort() when you want to sort an array and do not need to keep the original order, especially if performance and memory are critical. It is useful for quick in-place sorting.
Choose toSorted() when you want to keep the original array unchanged to avoid side effects or bugs. This is ideal in functional programming styles or when working with immutable data.
Key Takeaways
sort() changes the original array; toSorted() returns a new sorted array.toSorted() to avoid mutating data and keep code safer.toSorted() is newer and requires ECMAScript 2023 support.sort() may be slightly faster but can cause side effects.