Returning from a switch directly

When you have a switch statement residing in a function, it is sometimes best to simply return the intended values instead of having to rely on break statements. For example, in generateWelcomeMessage, we can simply return the welcome string. There's no need to go through the rigamarole of initializing a variable, assigning it, and breaking between cases:

function generateWelcomeMessage(language) {  switch (language) {    case 'DE':      return 'Willkommen!';    case 'FR':      return 'Bienvenue!';    default:      return 'Welcome!';  }}

Returning directly, in this way, is arguably clearer than breaking within each case, especially if each case's logic is fairly simple.

Get Clean Code in JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.