Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript sort()

sort orders array elements in place. Without a compare function it sorts as strings.

For numeric and custom ordering, you should pass a compare function.

Why We Need It

Sorting is common for lists, leaderboards, and UI tables.

Knowing how sort behaves avoids subtle bugs.

Syntax

array.sort()
array.sort((a, b) => a - b)

Basic Example

1. Default sort

const nums = [10, 2, 5];
nums.sort();

console.log(nums); // [10, 2, 5] as strings

Default sort is lexicographic, not numeric.

Real World Example

2. Numeric sort

const nums = [10, 2, 5];
nums.sort((a, b) => a - b);

console.log(nums); // [2, 5, 10]

Use a compare function for numeric order.

Multiple Use Cases

Default Sort

sort converts items to strings and sorts lexicographically by default.

This can surprise you with numbers like 10 coming before 2.

Compare Function

Provide a compare function for numeric or custom sorting.

Return a negative number for a before b, positive for a after b, and 0 for equal.

Mutation

sort mutates the original array.

Clone the array first if you need to keep the original.

More Examples

3. Sort objects

const users = [{ age: 30 }, { age: 20 }];
users.sort((a, b) => a.age - b.age);

console.log(users);

Compare object fields for custom sorting.

4. Clone before sort

const nums = [3, 1, 2];
const sorted = [...nums].sort((a, b) => a - b);

console.log(nums, sorted);

Clone to avoid mutating the original.

Comparison

Without

const nums = [10, 2, 5];
nums.sort();

With

const nums = [10, 2, 5];
nums.sort((a, b) => a - b);

Common Mistakes and Fixes

Assuming numeric sort

Provide a compare function for numbers.

Mutating original array

Clone before sorting if needed.

Returning boolean in compare

Return negative, zero, or positive numbers.

Interview Questions

Does sort mutate?

Yes, it sorts in place.

How do you sort numbers?

Provide a compare function like (a, b) => a - b.

How do you sort descending?

Use (a, b) => b - a.

Practice Problem

Practice: Sort an array of scores in descending order.

const scores = [20, 5, 30];
// TODO: sort descending

One Possible Solution

const scores = [20, 5, 30];
scores.sort((a, b) => b - a);
console.log(scores);

Frequently Asked Questions

Does sort mutate the array?

Yes, sort changes the original array.

Why does sort put 10 before 2?

Default sort compares strings, not numbers.

How do I sort descending?

Use (a, b) => b - a.

Try It Yourself

Try sorting numbers and strings to see differences.