Array

Array.prototype.sort

Sorts the elements of an array in place and returns the sorted array

Syntax

JavaScript
array.sort(compareFn?)

Parameters

ParameterTypeDescription
compareFn(a, b) => numberFunction that defines the sort order. Return negative if a < b, positive if a > b, 0 if equal

Return Value

The sorted array (same reference)

Examples

Basic Usage
const numbers = [3, 1, 4, 1, 5, 9];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 1, 3, 4, 5, 9]
Practical Example
const words = ['banana', 'apple', 'cherry'];
words.sort();
console.log(words); // ['apple', 'banana', 'cherry']
Advanced Usage
const users = [
  { name: 'Charlie', age: 25 },
  { name: 'Alice', age: 30 },
];
users.sort((a, b) => a.age - b.age);
console.log(users[0].name); // 'Charlie'

Understanding Array.prototype.sort

The Array.prototype.sort method in JavaScript sorts the elements of an array in place and returns the sorted array. It belongs to the Array object and is one of the most widely used methods for working with array values in modern JavaScript and TypeScript applications.

The method signature is array.sort(compareFn?). It accepts 1 parameter: compareFn. When called, it returns the sorted array (same reference). Understanding when and how to use sort() helps you write more expressive, readable code.

Common use cases for Array.prototype.sort include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like array-tosorted, array-reverse, array-toreversed, enabling you to chain operations together for complex data manipulation pipelines.

Browser support for Array.prototype.sort is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.

Browser Compatibility

Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.

Related Methods

More Array Methods

Other methods in the Array object

Related Tools

More Array Methods

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.