0
0
JavascriptComparisonBeginner · 3 min read

Sort vs toSorted in JavaScript: Key Differences and Usage

In JavaScript, 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.

Featuresort()toSorted()
Mutates original array?Yes, it sorts the array in place.No, returns a new sorted array.
Return valueThe sorted original array.A new sorted array copy.
Introduced inSince early JavaScript versions.ECMAScript 2023 (ES14).
UsageUse when you want to change the original array.Use when you want to keep original array intact.
PerformanceSlightly faster due to no copying.May be slower due to creating a new array.
ChainableYes, 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.

javascript
const numbers = [5, 3, 8, 1];
numbers.sort((a, b) => a - b);
console.log(numbers);
Output
[1, 3, 5, 8]
↔️

toSorted Equivalent

Here is the equivalent code using toSorted() which does not change the original array.

javascript
const numbers = [5, 3, 8, 1];
const sortedNumbers = numbers.toSorted((a, b) => a - b);
console.log(sortedNumbers);
console.log(numbers);
Output
[1, 3, 5, 8] [5, 3, 8, 1]
🎯

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.
Use 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.
Both accept the same comparison function for custom sorting.