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


#1

Hi All,

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

I’m doing this exercise:
https://www.codecademy.com/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/web-dev-intermediate-javascript-practice/lessons/intermediate-javascript-coding-challenge/exercises/sort-years

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]

console.log(sortYears(years));

//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,

Adam


#2

Hi, @adamfarkas

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

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

or

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

#3

Gosh, indeed (facepalm).

Thanks Denys!