0
0
Javascriptprogramming~10 mins

Switch statement in Javascript - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Switch statement
Start
Evaluate expression
Compare with case 1?
NoCompare with case 2?
Execute case 1
Break?
NoContinue to next case
Yes
Exit switch
The switch statement evaluates an expression and compares it to each case value. When a match is found, it executes that case's code until a break is encountered or the switch ends.
Execution Sample
Javascript
let day = 3;
switch(day) {
  case 1:
    console.log('Monday');
    break;
  case 3:
    console.log('Wednesday');
    break;
  default:
    console.log('Other day');
}
This code checks the value of 'day' and prints the matching weekday name or 'Other day' if no match.
Execution Table
StepExpression ValueCase ComparedMatch?ActionOutput
131NoCheck next case
233YesExecute case 3 blockWednesday
3Break encountered, exit switch
💡 Break statement stops execution after matching case 3.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
day3333
Key Moments - 2 Insights
Why does the switch stop after printing 'Wednesday'?
Because the break statement at the end of case 3 stops the switch from continuing to other cases, as shown in execution_table step 3.
What happens if we remove the break in case 3?
Without break, the switch would continue executing the next cases until it finds a break or ends, causing multiple outputs. This is called 'fall-through'.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 2?
AOther day
BMonday
CWednesday
DNo output
💡 Hint
Check the 'Output' column at step 2 in the execution_table.
At which step does the switch statement stop executing?
AStep 3
BStep 1
CStep 2
DIt never stops
💡 Hint
Look at the 'Action' column in execution_table where break is encountered.
If the variable 'day' was 2, what would be the output?
AMonday
BOther day
CWednesday
DNo output
💡 Hint
Since 2 matches no case, the default case runs as per the code in execution_sample.
Concept Snapshot
switch(expression) {
  case value1:
    // code
    break;
  case value2:
    // code
    break;
  default:
    // code
}

- Compares expression to cases
- Executes matching case
- Use break to stop fall-through
- Default runs if no match
Full Transcript
The switch statement starts by evaluating the expression. It then compares this value to each case in order. If a case matches, the code inside that case runs. The break statement stops the switch from running other cases. If no case matches, the default case runs. In the example, day equals 3, so it matches case 3 and prints 'Wednesday'. The break stops further execution. If break was missing, the switch would continue running the next cases, which can cause multiple outputs. This is called fall-through. Understanding where and why break is used helps control the flow inside switch statements.