Sort an Array Alphabetically using the sort Method

Sort an Array Alphabetically using the sort Method
0.0 0

#1

Tell us what’s happening:
Could someone explain to me why this passed the challenge.
I referenced the examples given and I’m curious as to why the way they wrote it out didnt work for me and this way did.

Your code so far


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

  
  // Add your code above this line

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/67.0.3396.87 Safari/537.36.

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


#2

Sort by default will sort based on character code (A, B, C,… then a, b, c…, etc). So you return the sorted array. The return a-b doesn’t do anything, because you’ve already returned and exited the function at the point

Edit just to expand on that, so there are two things here:

Firstly your function looks like this:

function alphabeticalOrder(arr) {
  return arr.sort....
  // Nothing after that return line does anything
  // JS doesn't need to look at it because the
  // function has already exited:
  return ....
}

And secondly, sort, if you don’t tell it how you want to sort, sorts things in this order (unicode points - this is just Latin alphabet bit of unicode, but it’s the one that applies here):

https://www.key-shortcut.com/en/writing-systems/abc-latin-alphabet/

So if you have a list of words like dog cat rabbit horse it will sort them cat dog horse rabbit. If you add Zebra (note uppercase), you’ll get Zebra, cat dog, horse, rabbit because uppercase Z comes before lowercase a. And if you have numbers, like 2, 3, 10, 1, sort will sort them 1, 10, 2, 3 (1 comes before 2, it doesn’t treat them as numbers)