It may be helpful to you to read the documentation on how the
.sort() function of the
Array object works. The MDN documentation is a great resource for this.
In any case, let’s step through what’s happening.
We are defining a function,
sortYears, using the arrow-notation. This function accepts a single input, the parameter
The “body” of our function is therefore:
arr.sort((x, y) => y - x);
Referring back to the documentation for
Array.prototype.sort(), we know that the
.sort() method requires a callback function. The callback function for
.sort() is what compares our values to work out how to sort them.
In our function, we are using an anonymous arrow-notation function as the comparator:
(x, y) => y - x
The output of the comparison function determines how the items are sorted. I’ll explain how this works in terms of the two values we are comparing, which are
If the return value of the comparison function is less than 0, then
x comes before
y in the sorted array.
If the return value of the comparison function is 0, then
y are unchanged.
If the return value of the comparison function is greater than 0, then
y comes before
x in the sorted array.
Let’s examine this in terms of our first two items from the array,
1999, and see how this works. We’ll say that
x = 1970, and
y = 1999.
Our function is
(x, y) => y - x, and with our values for
y this becomes
(x, y) => 1999 - 1970.
1999 - 1970 = 29, and since 29 is greater than 0 we know that 1999 ought to come before 1970 in our sorted array.
This process is repeated for all the items in the array.
Hopefully that explanation helps, but let us know if you’re still confused.