Picking the Members’ Note With switch
Under the race-day call, the members’ page posts a note for the members. Ruth’s Python script picks it with a match on the decision, and in this lesson, you ported that match to JavaScript’s switch statement.
Here’s Ruth’s step, with the decision set by hand to the main morning’s call:
decision = "racing"
match decision:
case "racing":
note = "Briefing at 9:30 in the clubhouse"
case "postponed":
note = "Next check at 11:00"
case "cancelled":
note = "See you next Saturday"
print(note)
- Ported line by line,
matchturns intoswitch, JavaScript’s statement for one value against fixed options. The value goes in parentheses,switch (decision), and the cases go in braces. Each case carries across as Python has it, with its value, its colon and its one note line, andprint(note)turns intoconsole.log(note);. - As with the
else ifchain,let note;goes above theswitch, so the note still exists after the closing brace. - JavaScript compares the decision with each case using
===, the same test you’d write in anifcondition. For these strings, that’s the test Python’s==makes. - Ported line by line, with each case holding only its note, the
switchruns without an error, but on a perfect racing morning, the page tells every memberSee you next Saturday. So does the calm morning; only the fog morning’s note is right. - The decision matches the first case, so execution starts there and sets the briefing note. The next case label doesn’t stop it, so execution runs on, sets the postponed note, then overwrites that with
See you next Saturday. The last assignment wins. - Running on like this is called fall-through. Each case is an entry point, not a closed block: execution starts at the matching case and runs through every case below it until something stops it. A postponed morning skips the first case, enters at the second and falls into the canceled note. A canceled morning enters at the last case, so its note is right only because nothing sits below it.
- In Python, a case ends at its last indented line, and only one case runs. You know
breakfrom Python’s loops, butmatchnever needs one. - In JavaScript,
breakon a case’s last line jumps past the rest of theswitch, to the line after it. End every case with one. The last case gets one too, so a case added below it later can’t fall in.