The sort() method of an array sorts the elements in the array in place. The default sort order is ascending which is done by converting the elements into strings and comparing UTF-16 values. This works good for strings but causes an unexpected behavior for numbers. Pass a custom sort function to sort() if you need to sort the elements in a way different than the default.

    
    const numbers = [2, 31, 500, 21, 10000];
    numbers.sort();
    console.log(numbers);
    // [10000, 2, 21, 31, 500]  // 10000 is not less than 2!


    // sort numbers lowest to highest
    const numbers1 = [2, 31, 500, 21, 10000];
    numbers1.sort((a, b) => (a - b));
    console.log(numbers1);
    // [2, 21, 31, 500, 10000]


    // sort numbers highest to lowest
    const numbers2 = [2, 31, 500, 21, 10000];
    numbers2.sort((a, b) => (b - a));
    console.log(numbers2);
    // [10000, 500, 31, 21, 2]


    // sort strings A - Z
    const names = ['Vic', 'Andy', 'Zack', 'Beth'];
    names.sort();
    console.log(names);
    // ["Andy", "Beth", "Vic", "Zack"]


    // sort strings Z - A
    const names1 = ['Vic', 'Andy', 'Zack', 'Beth'];
    names1.sort((a, b) => (a > b ? -1 : 1));
    console.log(names1);
    // ["Zack", "Vic", "Beth", "Andy"]
    // names1.sort().reverse() // the newest way