.sort() in JS: is MDN up to scratch?


Hi All,

This might be interesting to all who are learning .sort().

I’m doing this exercise:

Can anyone tell me why my original code did not work? It returns undefined. Despite MDN, that lays it out in in its Examples section in a similar fashion here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

//I wrote:

const sortYears = arr => {
arr.sort(function (a, b) {
return b - a;

const years = [1970, 1999, 1951, 1982, 1963, 2011, 2018, 1922]


//prints: undefined

The solution to the exercise was, although more elegant, essentially the same, they just used an arrow function inside the brackets:

const sortYears = arr => arr.sort((x, y) => y - x);

Can you tell me why my code returned undefined?

Many thanks,



Hi, @adamfarkas

Your function doesn’t have return statement , so returns undefined.

const sortYears = arr => {
    return arr.sort(function (a, b) {
        return b - a;


const sortYears = arr => arr.sort((a, b) => b - a);


Gosh, indeed (facepalm).

Thanks Denys!