Shouldn't this code give me the same results?

Hi Guys,

Thank you for taking a look here. I am doing code challenges and there is one about writing a function sortYears() that takes in an array of years and returns that array with the years sorted in descending order.

My first solution:

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

const years = [1970, 1999, 1951, 1982, 1963, 2011, 2018, 1922]
console.log(sortYears(years))

//results: undefined

Same solution written differently:

const sortYears = array => array.sort((a, b) => b - a);
const years = [1970, 1999, 1951, 1982, 1963, 2011, 2018, 1922]
console.log(sortYears(years))

//results: runs successfully

I am stunned and have no idea where I went wrong with the first one. Any thoughts?

Thanks,

Hi there, and welcome to the forums!

In the first solution the important thing to note is the nesting of return statements. The return keyword will always return from it’s most immediate function parent, which means that return b - a; returns from the array.sort() method. This is fine and correct behaviour, however the issue is that the value returned from array.sort() goes back into the function body. Then we need to be able to get that value back out of the function body, thus is also needs to be returned. Therefore it should be:

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

const years = [1970, 1999, 1951, 1982, 1963, 2011, 2018, 1922]
console.log(sortYears(years))

Where you have added another return keyword before the sorting function. This will return the final result from the function and do what you want it to do.

2 Likes

Hi Adam,

Thank you so much that makes all the more sense, much appreciated:)

Phuti