01 / 05
When === piles up
Sort by value with else if and you get size === "S", then size === "M", and the same variable name over and over.
For that situation there is another way to write it: switch.
The basics of syntax
INPUT · Slides
01 / 05
Sort by value with else if and you get size === "S", then size === "M", and the same variable name over and over.
For that situation there is another way to write it: switch.
02 / 05
In the brackets of switch goes the value you are examining, and inside the braces you line up case value:. Work starts at whichever case matched.
Each case ends with break;. That is the marker that says "and stop here".
const signal = "amber";switch (signal) { case "green": console.log("go"); break; case "amber": console.log("slow down"); break; case "red": console.log("stop"); break;}Result
slow down
03 / 05
A case is chosen when the value in the brackets and the value on the case are exactly the same. It is the same comparison as ===.
So numbers work as well as strings.
const rank = 2;switch (rank) { case 1: console.log("gold medal"); break; case 2: console.log("silver medal"); break; case 3: console.log("bronze medal"); break;}Result
silver medal
04 / 05
Forget the break and it carries straight on into the next case. Work belonging to a case that did not match gets done, which is almost always a bug.
Below, green matches and there is no break, so slow down comes out too.
const signal = "green";switch (signal) { case "green": console.log("go"); case "amber": console.log("slow down"); break;}Result
go slow down
05 / 05
switchifswitch is no good at "or more" and "or less". Pick by what you are trying to do. Time to write some.