The basics of syntax

INPUT · Slides

When nothing matches

01 / 04

No match means it walks straight past

When no case matches, a switch finishes without doing anything. There is no error either, so it is easy to miss that nothing happened.

Below, blue is on no case, so the signal message goes missing entirely.

const signal = "blue";switch (signal) {  case "green":    console.log("go");    break;  case "red":    console.log("stop");    break;}console.log("check done");

Result

check done

02 / 04

Catch it with default

That is what default is for. It runs when no case matched.

Unlike a case, you write no value after it. Think of it as the else of a switch.

const signal = "blue";switch (signal) {  case "green":    console.log("go");    break;  case "red":    console.log("stop");    break;  default:    console.log("cannot read the signal");}

Result

cannot read the signal

03 / 04

default goes last

By convention default goes at the very bottom. Down there nothing follows it to flow into, so you need no break.

When a case does match, default stays out of it. It is only ever the catch-all.

const size = "M";switch (size) {  case "S":    console.log("small");    break;  case "M":    console.log("medium");    break;  default:    console.log("we do not have that size");}

Result

medium

04 / 04

What being ready for the unexpected means

You do not write a default just to have another branch. You write it so that you find out when a value you did not plan for turns up.

Even if you are sure such a value cannot happen, the frightening outcome is the one where it does and nothing at all occurs. Time to write some.