The general syntax for this method is:
This method arranges the elements of an array into increasing order. For strings, this means alphabetical order. HOWEVER, the results are not always what we expect.
let letters = ['f', 'c', 'B', 'X', 'a']; letters.sort(); console.log(letters);
[ 'B', 'X', 'a', 'c', 'f' ]
let mixed = ['a', 'A', 20, 40]; mixed.sort(); console.log(mixed);
[ 20, 40, 'A', 'a' ]
When numbers and strings are sorted, the default order places numbers before all letters.
let numbers = [2, 8, 10, 400, 30]; numbers.sort(); console.log(numbers);
[ 10, 2, 30, 400, 8 ]
Later in this course, we will explore ways to fix this issue and correctly sort numerical arrays.