Sort an Array Alphabetically using the sort Method (that was weird)

Tell us what’s happening:

Might someone explain to me why this code worked for this challenge?

Your code so far


function alphabeticalOrder(arr) {
// Add your code below this line
return arr.sort();

// Add your code above this line
}
console.log(alphabeticalOrder(["a", "d", "c", "a", "z", "g"]));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36.

Challenge: Sort an Array Alphabetically using the sort Method

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/functional-programming/sort-an-array-alphabetically-using-the-sort-method

You are using array.sort function.

The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

If compareFunction is not supplied, all non- undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, “banana” comes before “cherry”. In a numeric sort, 9 comes before 80, but because numbers are converted to strings, “80” comes before “9” in the Unicode order. All undefined elements are sorted to the end of the array.

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

1 Like