[Solved] Why are these two pieces of code returning two different answers? Shouldn't they return the same answer?

Here’s a link to the coding challenge which i’m trying to do. My first solution returns the correct answer but my second solution returns an incorrect answer & i can’t understand why it’s happening.

const sortYears = array => {
  array.sort((first,second) => second-first );
  return array;
};

versus

const sortYears = array => {
  array.sort((first,second) => {second-first} );
  return array;
};

Hi,
your second example returns ‘undefined’ because that’s what a function returns if you don’t actively return anything. In shorthand syntax (your first example) the return is implied.

const fn = () => {'hello world!'}
const fn2 = () => {return 'hello world!'}
const fn3 = () => 'hello world!'


console.log(fn()) // undefined
console.log(fn2()) // "hello world!"
console.log(fn3()) // "hello world!"
3 Likes