JavaScript Interview Question #47

How does sort() work in JavaScript?

Objects, Arrays & Core Data Handling Junior Beginner

Quick Interview Answer

sort rearranges the original array in place. Without a compare function, elements are converted to strings and compared according to string ordering, which can produce unexpected results for numbers.

Detailed Explanation

sort rearranges the original array in place. Without a compare function, elements are converted to strings and compared according to string ordering, which can produce unexpected results for numbers.

For numeric ascending order, provide (a, b) => a - b; for descending order, use (a, b) => b - a. Because sort mutates the array, copy it first when the original order must be preserved.

Code Example

const numbers = [100, 2, 30];

console.log([...numbers].sort());
// [100, 2, 30] as string ordering

const ascending =
    [...numbers].sort((a, b) => a - b);

console.log(ascending); // [2, 30, 100]
console.log(numbers);   // original unchanged