Omitting optional else-branches
Sometimes, the else
in an if-else is optional. When the if
-condition makes the function end, we don’t have to nest the alternative case in else
at all.
const getWeekdayMood = isMonday => {
if (isMonday) {
// If the condition is `true`, the function returns a value and ends.
return 'Yes, a new week!'
} else {
// This code only happens if the condition is `false`.
return 'Time for another Monday soon!'
}
}
const getWeekdayMood = isMonday => {
if (isMonday) {
// Same deal: if this returns, the function ends. Nothing else happens.
return 'Yes, a new week!'
}
// Anything here also only happens if the condition is `false`. We don’t
// need to nest our code in an `else` for that.
// Look ma, no `else`!
return 'Time for another Monday soon!'
}