Javascript: Lexicographic Sorting

In Javascript, what would you expect the following expression to produce?

[1, 10, 8].sort();

If you thought this would evaluate to [1, 8, 10], you would benefit from a better understanding of the way Javascript deals with arrays. The above expression actually evaluates to:

[1, 10, 8].sort() = [1, 10, 8]

Why is this? The answer:

  • Javascript arrays can contain any valid value type, including null, String, Number, Boolean or another Object;
  • therefore, the Array.prototype.sort() method first applies the toString() method on each element of the array, and then sorts them in lexicographic order — also known as alphabetical sorting — as opposed to numerical order.