0%

javascript-return-undefined-in-else-branch

Dost it make sense to return undefined in else branch?

Today, I noticed a code snippet during code review, it looks like this:

1
2
3
4
5
6
7
const getUserInfo(user: User) {
if (user.isActive) {
return user.info;
} else {
return undefined;
}
}

The code is trying to get the user info, if the user is active, it will return the user info, otherwise, it will return undefined. But does it make sense to return undefined in the else branch? In JavaScript, if a function does not return anything, it implicitly returns undefined. So, the above code can be refactored to:

1
2
3
4
5
const getUserInfo(user: User) {
if (user.isActive) {
return user.info;
}
}

Similarly to the following code.

1
2
3
4
5
6
7
8
9
const fetchData = async () => {
try {
const data = await fetch('https://api.example.com/data');
return data.json();
} catch (error) {
console.error(error);
return undefined;
}
};

Which can be simplified to:

1
2
3
4
5
6
7
8
const fetchData = async () => {
try {
const data = await fetch('https://api.example.com/data');
return data.json();
} catch (error) {
console.error(error);
}
};