Omitting optional else-branches

Posted on

Sometimes, the else in an if-else is optional. When the if-branch ends with a return keyword, we don’t have to nest the alternative case in else at all. We can place the code that would usually be under the else-condition out to the same indentation as the if branch.

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!"
}
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!"
}
Debug
none
Grid overlay