Default sorting based on String

While learning the basics of JS, I came across something strange about how in-built array functions work, specifically sort().

Let’s try to sort an integer array:

var values = [10, 1, 20, 5, 12];
values.sort();

// Output
// 1, 10, 12, 20, 5
// expected: 1, 5, 10, 12, 20.

Why?

The sort() method calls the String() function on each element of array and compares the string value of all the elements. Finally, sorts them according to the comparison result. That’s why 10, 20 comes before 5.

“Correct” Sort:

In case you actually want to sort an array based on their integer value then sort() function provides an overload in which you can pass a Comparison Function

// Compare function for ascending order of int
function compareAscending(value1, value2){
    if(value1 < value2){
        return -1;
    }else if(value1 > value2){
        return 1;
    }else {
        return 0;
    }
}

values.sort(compareAscending);

// Output: 1, 5, 10, 12, 20