In regards to Javascript, how important is it to know how to manually sort things (i.e. the inner machinations of the sort() algorithm, etc.)? Is there any reason I shouldn’t rely on the inbuilt Array.sort() function alone? Also, If someone could give me a brief rundown on how sort() works exactly (for instance, why does a - b work?) and the different types of sort, that’d be great.

The way sort’s algorithm works is different in the mainstream browsers

Typical properties one looks for in a sorting algorithm is whether it’s *stable* (preserves order of elements if they compare the same), and *performant* (how it scales with larger arrays, and/or performance heuristics)

Recently (mid last year) it changed again in Chrome (really interesting blog post here): https://v8.dev/blog/array-sort

You probably don’t need to be concerned with hand-rolling a sorting algorithm yourself, the one implemented in Chrome/Firefox is *good enough* for most cases

How `Array.prototype.sort()`

works is by taking in a *comparator* function which it uses to compare elements to know which side they need to be on.

This comparator function says, for `a`

and `b`

, if `f(a,b) < 0`

then `a`

must be before `b`

, `f(a,b) == 0`

then it doesn’t matter which order, and `f(a,b) > 0`

then `a`

must be after `b`

in the list

The default comparator function coerces values into strings and calculates a side based on string comparisons

You might wonder why that was chosen over numerical sorting, but it’s because arbitrary values can be in a list, and it’s the ‘safest’ default one can pick, as many values can be coerced into a string to be compared in JS

you should know how write algorithms in general. sort() is just a shortcut

thats like asking should why should i learn math if i have a calculator

.sort() uses TimSort.

Worse-case time complexity O(n log n) and best case is O(n). You’re unlikely to find something faster to sort your data.

when in doubt refer to your bible