0

    const index = users.findIndex((user) => user.id === id )
       console.log(index)

This Code Run perfectly. But this code showing wrong result

const index = users.findIndex((user) => {
        user.id === id
    })

    console.log(index)

Can anybody please explain me, Why using second bracket showing wrong result?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Rupam
  • 75
  • 1
  • 9
  • Here, different types of the function declaration was explained pretty well: https://www.freecodecamp.org/forum/t/function-inside-a-round-brackets/299464/2 – Diyorbek Sadullaev Jun 15 '20 at 19:49

3 Answers3

0

Because nothing is returned in the second example. By omitting the brackets, you are causing a return. Within the brackets you must use a return statement;

const index = users.findIndex((user) => user.id === id )

is the same as writing

const index = users.findIndex((user) => { return user.id === id; });

If there are brackets, then you must use a return statement. If there are no brackets then javascript implicitly returns the evaluated expression - user.id === id.

Dylan Kerler
  • 2,007
  • 1
  • 8
  • 23
0

When using second brackets that is {}, you have to use return the statement.

If it's multi-line code then you have to use {} and return. If it's one line, you don't have to use that.

const index = users.findIndex((user) => {
       return user.id === id
    });

console.log(index)

You can refer the link below to see how arrow functions work, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Nishant
  • 466
  • 2
  • 15
0

It's because when you open the brackets you need to state a return. For example, this -> (parameter) => something <- is equal to this -> (parameter) => {return something} <- The main difference between those two is that in the second case you can put more code and in the first case is only a return.

#1 Example

const sum = (a, b) => a + b //It will return the sum of a+b

#2 Example

const sum = (a, b) => {
  console.log(`adding ${a} + ${b}`);
  const result = a + b;
  return result;
}
Syntle
  • 5,168
  • 3
  • 13
  • 34