0

I'm wondering why arry.find() is working if I write it like this:

const tour = tours.find(el => el.id === id);

But not if I write the arrow function like that:

const tour = tours.find((el) => {el.id === id});

Can someone explain this? In both cases I give a function as parameter.

2 Answers2

2

The first one is a shorted line for:

const tour = tours.find(el => { return el.id === id });

You need to add the return in the second case otherwise you return undefined and filter works only with a truethy return.

Sascha
  • 4,576
  • 3
  • 13
  • 34
0

Because, you need to return either true or false in your callback function. So this is how your code should go(in the second case when you use code blocks):

const tour = tours.find((el) => {return el.id === id});

However, arrow functions have a shorthand, where you do not need to use code blocks if it is a one line statement, and it automatically returns the result of the statement, so you don't need to explicitly use return to return the result of the conditional statement.

lanxion
  • 1,350
  • 1
  • 7
  • 20