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!'
}

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.