0

So I was making a get user email function and came up with this.

This is the function that works perfectly.

const getMail = (users, userLoggedIn) =>
    users?.filter((userToFilter) => userToFilter !== userLoggedIn?.email)[0];

export default getMail;

Here is the 2nd function, that is not working as it's returning undefined.

const getMail = (users, userLoggedIn) => {
    users?.filter((userToFilter) => userToFilter !== userLoggedIn?.email)[0];
}

export default getMail;
Gourav Singh Rawat
  • 421
  • 1
  • 7
  • 17

2 Answers2

1

The second function is not returning anything, you will have to use return statement when wrapping the function body in curly brackets.

If you do not put brackets around your arrow function body the return statement can be ommitted. So the first function works.

In the second function you wrote curly brackets { and you would need to add a return statement.

So these functions are equal:

// #1
const getMail = (users, userLoggedIn) =>
  // curly brackets ommitted. THe function only consists of "1" statement 
  // and the result will automatically returned.
  users?.filter((userToFilter) => userToFilter !== userLoggedIn?.email)[0];

export default getMail;

// #2 
const getMail = (users, userLoggedIn) => {
    // you need to explicitly use "return" to return the value.
    return users?.filter((userToFilter) => userToFilter !== userLoggedIn?.email)[0];
}

export default getMail;
Silvan Bregy
  • 2,544
  • 1
  • 8
  • 21
1

You're using a shorthand without even knowing it. Without the {} after the arrow it will by default return whatever comes after the arrow. Otherwise you have to use the return statement.

const getMail = (users, userLoggedIn) => {
    return users?.filter((userToFilter) => userToFilter !== userLoggedIn?.email)[0];
}

export default getMail;
Mikaels Slava
  • 186
  • 2
  • 8