"Sort Arrays with .sort" HELP!

"Sort Arrays with .sort" HELP!


This is in reference to the “Sort Arrays with .sort” challenge…

I was able to pass this challenge (I basically had to do the opposite of what was shown in the example)- but I don’t understand what a and b are- can anyone explain?

Below is the function solved:

var array = [1, 12, 21, 2];

// Only change code below this line.

array.sort(function (a,b){
  return b-a;



I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

.sort needs a callback function to determine how to sort the array. From MDN:

If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:

  • If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
  • compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.


Thanks Kev! This was my fault for not seeing the link to the MDN page in the challenge’s direction- thanks for the help with the challenge though- and thanks for correcting the question format!