Course contentsShow
← JavaScript
Lesson 327 of 2,7239. Control FlowFree lesson

Switch with Return Statements

Return directly from case blocks to eliminate the need for break statements in functions.

Switch with Return Statements

You'll learn how returning directly from case blocks eliminates the need for break statements inside functions.

The Core Idea

When a switch statement lives inside a function, you can use return instead of break to exit each case. Since return exits the entire function, it automatically prevents fall-through—no break needed.

This makes your code cleaner and more concise, especially when your switch's purpose is to determine what value the function should return.

How It Works

Without return (traditional approach):

function getColor(code) {
  let color;
  switch (code) {
    case 1:
      color = 'red';
      break;
    case 2:
      color = 'blue';
      break;
    default:
      color = 'unknown';
  }
  return color;
}

With return (streamlined):

function getColor(code) {
  switch (code) {
    case 1:
      return 'red';
    case 2:
      return 'blue';
    default:
      return 'unknown';
  }
}

Notice how the second version is shorter and clearer? Each case immediately returns its value and exits the function. No intermediate variable, no break statements cluttering the code.

Think of It This Way

Imagine a vending machine where pressing a button (the case) instantly dispenses your item (the return) and you walk away. You don't need a "stop" sign (break) because you're already leaving with your product.

Key Takeaway: When using switch inside a function to compute a return value, use return directly in each case—it's cleaner than break and eliminates the need for a variable to hold the result.