'Difference between these two functions in JS that I'm querying from firestore [duplicate]

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;


Solution 1:[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;

Solution 2:[2]

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;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Silvan Bregy
Solution 2 Mikaels Slava