-2

Why does the addition of {} in the second sort function "break" the sort (change it back to sorting alphabetically?):

console.log([10, -2, 49].sort((a,b) => a-b))
console.log([10, -2, 49].sort((a,b) => {a-b}))

This is more of a why does JS do this type of question rather than a fix my code type of question.

Paul Sender
  • 376
  • 2
  • 19
  • 1
    Because one has a return value and the other does not. Please read about different ways to return from an arrow function [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) – Brian Thompson Jun 29 '21 at 13:47
  • The second one adds a block which has no return statement – evolutionxbox Jun 29 '21 at 13:47

3 Answers3

4

The sort method's callback function in javascript needs to return a value, when you put {} around the function content you are essentially returning undefined from the function and your code inside the function is just an expression being executed inside it

When you use {} you need an explicit return statement to return the value

console.log([10, -2, 49].sort((a,b) => a-b))
console.log([10, -2, 49].sort((a,b) => {return a-b;}));

In the first case it works because when you write the function with that syntax, it has an implicit return.

You can know more about explicit and implicit return in this post:

Arrow functions and the use of parentheses () or {} or ({})

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
1

Okay, this is common confusion , / FUNCTION 1

const func = (a,b ) => a+b 

Equivalent to , Function 2

const func = (a,b) => {
return (a+b)
}

So when you us e curly braces , you must explicitly use return keyword , where using () doesn't require using return keyword.

Sifat Amin
  • 1,091
  • 6
  • 15
1

When you have an arrow function (the =>), you can have single-line statements which auto-return an expression, or multiline statements, which require {} around the statements and thus require a return. By adding the {}, you get the multiline statement form. So you need to add a return within the curly braces, or nothing is returned.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Note, if you want to return an object from a single-line array function statement, wrap it in parentheses:

((a, b) => ({ c: a + b }))(1, 2) // {c: 3}
Jared Farrish
  • 48,585
  • 17
  • 95
  • 104