Module 4: Control Flow – Conditionals and Loops
Switch Statements
The switch
statement provides an alternative way to execute different blocks of code based on the value of an expression. It's often used when you have multiple specific values to check against.
let dayOfWeek = "Monday"; switch (dayOfWeek) { case "Monday": console.log("Start of the work week."); break; // The break statement exits the switch block. case "Friday": console.log("Almost weekend!"); break; case "Saturday": case "Sunday": // Multiple cases can share the same code block console.log("It's the weekend!"); break; default: // Optional: executes if no case matches console.log("It's a regular day."); }
Key points about switch
:
- The expression in
switch (expression)
is evaluated once. - The value of the expression is compared with the values of each
case
using strict equality (===
). - If a match is found, the code block associated with that
case
is executed. - The
break
statement is crucial. If omitted, execution will "fall through" to the nextcase
block, regardless of whether its condition matches. - The
default
case is optional and runs if no othercase
matches.