cf.completefrontendCode editorOpen lab
THE JAVASCRIPT FIELD GUIDE

The switch statement

Choose between many JavaScript cases with strict matching, break, default, intentional fallthrough, and object lookup alternatives.

By the end, you can
  • 01
    Match cases exactlyExplain why switch uses the same strict matching idea as ===.
  • 02
    Control fallthroughUse break, intentional grouped cases, return, and default safely.
  • 03
    Choose the cleaner patternDecide between switch, if/else chains, and object lookups.

Choose one path from many exact cases

INTERACTIVE

The switch statement is a control-flow tool for one common shape of decision: you have one value, and you want to jump to one of several named cases. It is a cousin of an if / else if chain, but it reads best when the question is “Which exact value is this?”

You already met comparisons, including the difference between === and ==. A switch uses strict matching like ===. You also saw in Type conversion that inputs usually arrive as strings. Those two facts matter here: the string "1" will not match the number case 1.

Real-life analogyA switch is like a vending machine

Imagine typing B3 into a vending machine. The machine does not inspect A1, A2, A3, and slowly wander downward. It jumps straight to the matching slot. A switch has the same feel: one value, a menu of exact labels, and one starting point.

In real life: You press B3
In JavaScript: switch (slot) evaluates one value
In real life: The machine jumps to slot B3
In JavaScript: JavaScript jumps to the matching case
In real life: A sold-out or wrong code needs a fallback
In JavaScript: default handles none of the above
In real life: The snack drops and the action is done
In JavaScript: break or return ends that branch

Where the analogy stops: A vending machine stops automatically after one snack. JavaScript does not: without break or return, it can keep running into the next case.

Here is the shape you will practice throughout the lesson:

The basic shapePop out in the code editor (opens in a new tab)JavaScript
switch (value) {  case "first":    // statements for first    break;  case "second":    // statements for second    break;  default:    // statements when no case matched}

The important rule is not “run one block.” The actual rule is: find the first matching case, then run statements downward until something stops the switch. Most of the lesson is about what counts as a match, and what stops the downward flow.

Matching with strict equality

TRY IT

Every case label is compared with the switch value using strict matching, the same idea as ===. JavaScript does not helpfully convert strings to numbers for you while choosing a case.

String one and number one are differentPop out in the code editor (opens in a new tab)JavaScript
const input = "1";let label; switch (input) {  case 1:    label = "number one";    break;  case "1":    label = "string one";    break;  default:    label = "unknown";} console.log(label);

This prints string one. The first case is the number 1, but the switch value is the string "1". The second case has the same type and value, so it matches.

Try the "1" versus 1 match
Strict matching sourcePop out in the code editor (opens in a new tab)JavaScript
const input = "1";const value = Number(input); // or keep input as a string switch (value) {  case 1:    console.log("number one");    break;  case "1":    console.log("string one");    break;  default:    console.log("unknown");}
Resultstring
switch value"1"
typeofstring
chosen labelstring one
Try it yourself

The switch value is "1" (string). It chooses "string one".

A small live version of the strict-matching demo. It does not evaluate your code; it switches between the two safe examples shown in the source.
Fix the type before the switch

If a prompt, URL parameter, or form field gives you text, decide what type your cases should use. Convert once with Number(input) when your cases are numbers, or write string cases when the codes are meant to be text.

You may see a pattern called switch (true) for ranges:

Ranges with switch truePop out in the code editor (opens in a new tab)JavaScript
const score = 82;let grade; switch (true) {  case score >= 90:    grade = "A";    break;  case score >= 80:    grade = "B";    break;  default:    grade = "keep practicing";} console.log(grade);

This works because each case expression produces a boolean, and the first true case matches switch (true). Use it sparingly. For most beginner code, a normal if / else if chain is clearer for ranges because each line is visibly a condition.

break and fallthrough

STEP THROUGH

A switch does not automatically stop at the next case label. Once a match is found, JavaScript keeps running statements downward. A break statement exits the switch.

Real-life analogyFallthrough is water flowing down stairs

Picture a staircase in the rain. Once water lands on one step, it keeps flowing down to the next step unless something blocks it. Switch execution is the same: a matching case is the step where execution begins, not a sealed room.

In real life: Water lands on a stair
In JavaScript: Execution starts at the matching case
In real life: It flows to lower stairs
In JavaScript: Statements below also run
In real life: A dam stops the water
In JavaScript: break exits the switch
In real life: No dam means the next step gets wet
In JavaScript: Missing break means fallthrough

Where the analogy stops: Water has no intention. Code can use fallthrough intentionally, but you must make that intention obvious.

Use this recorded replay to see the difference. Pick yellow, then remove yellow’s break. The same input changes from slow down to go because the green case runs after yellow.

Step through a traffic-light switch
Step 0 of 7Ready
Your turn: follow the blue line

Pick a color, then step through the real switch. Try yellow with and without the break to see fallthrough.

Running in
  1. script
Next: line 1
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
let action = ""; switch (color) {  case "red":    action = "stop";    break;  case "yellow":    action = "slow down";    break;  case "green":    action = "go";    break;  default:    action = "check the signal";} console.log(action);
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
Choose the switch value:
Change the yellow case:

Changing either setting starts a fresh recorded run.

A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.
Intentional fallthrough should look intentional

Grouping cases is common and safe when the earlier cases have no statements. If you intentionally run statements and then fall into a later case, add a comment like // falls through. ESLint’s no-fallthrough rule respects that convention; the Linting lesson explains why teams use rules like this.

default is the none-of-the-above case

EDGE CASES

The default label runs when no case matched. It is the “none of the above” button. Most examples place it last because that is easiest to read, but JavaScript allows it anywhere.

default can appear in the middlePop out in the code editor (opens in a new tab)JavaScript
const size = "large";let price; switch (size) {  default:    price = "ask staff";    break;  case "small":    price = 3;    break;  case "large":    price = 5;} console.log(price);

With size set to "large", JavaScript skips the middle default and matches case "large". The output is 5. Default’s position did not make it run first.

But default follows the same fallthrough rules as every other label:

default can fall through tooPop out in the code editor (opens in a new tab)JavaScript
const size = "medium";let price = ""; switch (size) {  default:    price = "unknown";  case "large":    price = price + " size";} console.log(price);

Here "medium" matches no case, so default runs and sets price to "unknown". There is no break, so execution continues into the "large" case body and appends " size". The output is unknown size.

Practical switch patterns

PATTERNS

The safest fallthrough is an empty case that groups several labels before one shared body. Days of the week are a classic example:

Group Saturday and SundayPop out in the code editor (opens in a new tab)JavaScript
const day = "Saturday";let kind; switch (day) {  case "Saturday":  case "Sunday":    kind = "weekend";    break;  default:    kind = "weekday";} console.log(kind);

Saturday has no statements of its own, so it falls into Sunday’s shared body. That is intentional and easy to read. The shared body still ends with break.

A switch inside a function often returns from each case. A return exits the whole function, so it also prevents fallthrough:

Return leaves the whole functionPop out in the code editor (opens in a new tab)JavaScript
function shipping(speed) {  switch (speed) {    case "overnight":      return 25;    case "standard":      return 7;    default:      return 0;  }} console.log(shipping("standard"));

This prints 7. Once return 7 runs, the function is done. A break after that return would be unreachable.

You will use switches for small menus: keyboard commands, status strings, route names, display modes, and other exact labels. If the list grows large or comes from data, the next section gives you a cleaner alternative.

Object lookups instead of switch

SORTER

Sometimes a switch is only a long table: this key means that value. For that shape, a simple object literal plus bracket access is often shorter and safer.

A price table as an objectPop out in the code editor (opens in a new tab)JavaScript
const prices = {  apple: 1.2,  banana: 0.5,  cherry: 2,}; const fruit = "banana";const price = prices[fruit] ?? "unknown";console.log(price);

prices[fruit] asks the object for the value stored at the key in fruit. If that key is missing, it would produce undefined, so the nullish coalescing operator ?? gives a fallback. Object basics get a full lesson in Stage 3; for now, read the braces as a tiny lookup table. The Map data structure comes later in Map & Set.

Compare switch with an object lookup
Lookup sourcePop out in the code editor (opens in a new tab)JavaScript
const prices = {  apple: 1.2,  banana: 0.5,  cherry: 2,}; const fruit = "banana";const price = prices[fruit] ?? "unknown";console.log(price);
Same behavior?yes
fruitbanana
switch0.5
lookup0.5
Try it yourself

For banana, the switch returns 0.5 and the lookup returns 0.5.

Both approaches are real functions from the lesson tests. The lookup is shorter when keys map directly to values.
switch vs if/else vs object lookup
Questionswitchif / elseobject lookup
Best questionWhich exact value is this?Which condition is true?What value belongs to this key?
Typical inputA string or number with known casesRanges, multiple variables, or truthy checksA string key like a product name
Main riskForgetting break and falling throughPutting conditions in the wrong orderMissing keys returning undefined
Dynamic dataAwkward: cases are written in codeAwkward for long listsGreat: the object can be created or updated
Beginner ruleUse it for a short menu of exact choicesUse it when each branch asks a different questionUse it when keys map directly to values
switch, if/else, or lookup object?
  • A command can be exactly copy, paste, cut, or undo.
  • If temperature is below 0, below 20, or higher.
  • Fruit names map directly to prices loaded from data.
  • Saturday and Sunday should run the same branch.
  • A role name maps to a small handler function.
  • Check empty name, invalid email, then short password in order.
Try it yourself
0 of 6 correct

Sort each scenario by the clearest decision shape. There can be working alternatives, but choose the one that reads best for a beginner maintaining the code.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Common misconceptions

“switch uses loose equality.”

It does not. case 1 will not match "1". Convert the value first or use string cases.

“Only the matching case runs.”

The matching case is where execution starts. Statements below can run too unless break, return, or the end of the switch stops them.

“default must be last.”

It can appear anywhere. Last is usually clearest, and it still follows fallthrough rules.

“Fallthrough is always a bug.”

Missing break is often a bug, but grouped cases like Saturday and Sunday intentionally share a body. Add a comment when non-empty fallthrough is deliberate.

“Each case has its own block automatically.”

Cases share the switch block. That means two let declarations with the same name can clash before any case runs.

This is a SyntaxErrorPop out in the code editor (opens in a new tab)JavaScript
switch ("a") {  case "a":    let message = "alpha";    break;  case "b":    let message = "bravo";    break;}
Braces give each case its own blockPop out in the code editor (opens in a new tab)JavaScript
switch ("a") {  case "a": {    let message = "alpha";    console.log(message);    break;  }  case "b": {    let message = "bravo";    console.log(message);    break;  }}
Professional habit

If a case declares let or const, wrap that case body in braces. It makes the scope visible and prevents future declarations from colliding.

Practice: trace and refactor switches

5 EXERCISES

For prediction exercises, do not run the code first. Find the matching case, then read downward until a stop. After you answer, paste it into your console to prove it.

Exercise 1 · Warm-upPredict the missing break

What exact text does this code print?

Starter codePop out in the code editor (opens in a new tab)JavaScript
let badge = "";

switch ("silver") {
  case "gold":
    badge = "Gold";
    break;
  case "silver":
    badge = "Silver";
  case "bronze":
    badge = badge + " + Bronze";
    break;
  default:
    badge = "No badge";
}

console.log(badge);

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · PracticeFix the "1" versus 1 mismatch

    First predict what the buggy code prints. Then change it so the first page is selected.

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    const input = "1";
    let page;
    
    switch (input) {
      case 1:
        page = "first";
        break;
      default:
        page = "not found";
    }
    
    console.log(page);

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeGroup weekend cases

      Write or explain a switch where Saturday and Sunday both produce weekend.

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      const day = "Saturday";
      let kind;
      
      switch (day) {
        case "Saturday":
        case "Sunday":
          kind = "weekend";
          break;
        default:
          kind = "weekday";
      }
      
      console.log(kind);

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · ChallengeConvert a switch to an object lookup

        Refactor the function without changing its behavior. It should still return ❓ for an unknown status.

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        function emojiForStatus(status) {
          switch (status) {
            case "success":
              return "✅";
            case "warning":
              return "⚠️";
            case "error":
              return "🚨";
            default:
              return "❓";
          }
        }
        
        console.log(emojiForStatus("warning"));

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeAdd a default case

          Add a fallback so unknown drink size codes return unknown size.

          Starter codePop out in the code editor (opens in a new tab)JavaScript
          function drinkSize(code) {
            switch (code) {
              case "S":
                return "small";
              case "M":
                return "medium";
            }
          }
          
          console.log(drinkSize("XL"));

          Answer, then press Check. Spacing and letter case don’t matter.

            Quiz: check your understanding

            7 QUESTIONS

            Read each code sample exactly. Your first-try score matters less than the explanation after each choice.

            Lesson quiz · 7 questionsScore: first tries count
            1. Question 1 of 7How does switch compare its value with each case?

              Choose an answer to see the explanation.

            2. Question 2 of 7What does strict matching print here?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              const value = "1";
              
              switch (value) {
                case 1:
                  console.log("number");
                  break;
                case "1":
                  console.log("string");
                  break;
                default:
                  console.log("other");
              }

              Choose an answer to see the explanation.

            3. Question 3 of 7What does the missing break print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              let result = "";
              
              switch ("A") {
                case "A":
                  result += "Alpha";
                case "B":
                  result += "Beta";
                  break;
              }
              
              console.log(result);

              Choose an answer to see the explanation.

            4. Question 4 of 7Which is the clearest way to handle Saturday and Sunday the same way?

              Choose an answer to see the explanation.

            5. Question 5 of 7What does default fallthrough print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              let size = "";
              
              switch ("medium") {
                default:
                  size = "unknown";
                case "large":
                  size = size + " size";
              }
              
              console.log(size);

              Choose an answer to see the explanation.

            6. Question 6 of 7Why might you choose an object lookup instead of a switch?

              Choose an answer to see the explanation.

            7. Question 7 of 7What happens when a return runs inside a switch inside a function?

              Choose an answer to see the explanation.

            Key takeaways

            • A switch evaluates one value, then compares it to case labels using strict matching like ===.
            • Execution starts at the matching case and continues downward until break, return, or the end of the switch.
            • default runs when no case matches. It can be placed anywhere, but it can also fall through if you omit break.
            • Grouped empty cases are a clear way to share one body; non-empty intentional fallthrough needs a comment.
            • Use object lookups when keys map directly to values. Use if / else when each branch asks a different condition.

            Remember the one-liner.
            A switch jumps to the first strictly matching case, then runs until something stops it.

            Up next: Loops: while & for. You will repeat work and see that break can exit loops too.

            CompleteFrontend Clear concepts. Working examples.