What is the difference between sort and toSorted in JavaScript?

javascript array tosorted

JavaScript array manipulation has evolved significantly with the introduction of new methods that provide developers with more flexibility and safer approaches to data handling. Understanding the difference between the traditional sort method and the newer toSorted method is crucial for modern JavaScript development.

Table of Contents

Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


Understanding the Core Difference

The primary distinction lies in how these methods handle the original array. The sort method modifies the array in place, while toSorted is a copying version that returns a new array with the elements sorted without affecting the source data.

const numbers = [3, 1, 4, 1, 5]

// Using sort - mutates original array
const sortedWithSort = numbers.sort()
console.log('Original after sort:', numbers) // [1, 1, 3, 4, 5]
console.log('Result:', sortedWithSort) // [1, 1, 3, 4, 5]

// Reset array
const arr = [3, 1, 4, 1, 5]

// Using toSorted - preserves original array  
const sortedWithToSorted = arr.toSorted()
console.log('Original after toSorted:', arr) // [3, 1, 4, 1, 5]
console.log('Result:', sortedWithToSorted) // [1, 1, 3, 4, 5]

How the sort Method Works

The sort method has been a fundamental feature of JavaScript since its early days. When called, this method arranges array elements in ascending order by default, converting elements to strings and comparing their UTF-16 code points.

const months = ['March', 'Jan', 'Feb', 'Dec']
months.sort()
console.log(months) // ['Dec', 'Feb', 'Jan', 'March']

const numeric_array = [10, 5, 40, 25, 1000, 1]
numeric_array.sort()
console.log(numeric_array) // [1, 10, 1000, 25, 40, 5] - unexpected for numbers!

To properly sort numbers in ascending order, you need a compare function:

const numbers = [10, 5, 40, 25, 1000, 1]
numbers.sort((a, b) => a - b)
console.log(numbers) // [1, 5, 10, 25, 40, 1000]

The toSorted Method: A Modern Approach

The toSorted method was introduced as part of the ECMAScript specification to provide a non-mutating alternative. This method returns a new array with elements sorted in ascending order, leaving the original array unchanged.

const originalNumbers = [64, 34, 25, 12, 22, 11, 90]

// Ascending order with toSorted
const ascending = originalNumbers.toSorted((a, b) => a - b)
console.log('Ascending:', ascending) // [11, 12, 22, 25, 34, 64, 90]
console.log('Original unchanged:', originalNumbers) // [64, 34, 25, 12, 22, 11, 90]

// Descending order
const descending = originalNumbers.toSorted((a, b) => b - a)
console.log('Descending:', descending) // [90, 64, 34, 25, 22, 12, 11]

Working with Compare Functions

Both methods accept a compare function as an optional parameter. When this function is omitted, elements are converted to strings and sorted alphabetically. The compare function defines the sort order by returning:

  • A negative value when the first element should come before the second
  • Zero when elements are equal
  • A positive value when the first element should come after the second
const arr = [
  { name: 'John', age: 30 },
  { name: 'Jane', age: 25 },
  { name: 'Bob', age: 35 }
]

// Sort by age using toSorted
const sortedByAge = arr.toSorted((a, b) => a.age - b.age)
console.log('Sorted by age:', sortedByAge)
// Output: [{ name: 'Jane', age: 25 }, { name: 'John', age: 30 }, { name: 'Bob', age: 35 }]

// Original objects array remains unchanged
console.log('Original array:', arr)

Browser Support and Compatibility

The toSorted method is a relatively new feature introduced in modern browsers. It’s supported in:

  • Chrome/Edge: version 110+
  • Firefox: version 115+
  • Safari: version 16+
  • Node.js: version 20+

For projects targeting older browsers, you can create a similar function:

function toSortedPolyfill(arr, compareFn) {
  return [...arr].sort(compareFn)
}

const numbers = [3, 1, 4, 1, 5]
const result = toSortedPolyfill(numbers, (a, b) => a - b)
console.log('Result:', result) // [1, 1, 3, 4, 5]
console.log('Original:', numbers) // [3, 1, 4, 1, 5]

Best Practices and When to Use Each Method

Use sort when:

  • You want to mutate the original array
  • Memory efficiency is critical
  • Working with legacy code that expects in-place sorting

Use toSorted when:

  • You need to preserve the original array
  • Working with React.js functional components where immutability is preferred
  • Creating multiple sorted versions of the same data
  • Following functional programming principles

Performance Considerations

The sort method typically performs better in terms of memory usage since it doesn’t create a new array. However, toSorted provides better safety by preventing accidental mutations. For beginners learning JavaScript, toSorted helps avoid common problems related to unexpected array modifications.

// Example demonstrating why toSorted is safer
const originalData = [5, 2, 8, 1, 9]

function processData(data) {
  return data.toSorted((a, b) => b - a) // Safe - doesn't mutate input
}

const processed = processData(originalData)
console.log('Processed:', processed) // [9, 8, 5, 2, 1]
console.log('Original preserved:', originalData) // [5, 2, 8, 1, 9]

The toSorted method represents JavaScript’s evolution toward more predictable and safer array manipulation, making it an essential tool for modern developers who value code reliability and maintainability.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.