switch Statement — JS Technical Interview Questions & Answers
Multi-way branching on a single value.
switch Statement
- Multi-way branching on a single value.
- switch Statement is JavaScript control flow. if / switch pick a branch. for / while repeat. Condition must be boolean-ish: if (marks >= 40). Use === not =.
- for (let i = 0; i < arr.length; i++) or for (const m of marks). while needs a change inside or it loops forever.
- Trap: = inside if. Trap: off-by-one on the last index.
Technical Interview Tip: switch Statement: tiny marks example, predict the path.
Code Examples for switch Statement
switch Statement — working example
const marks = 72;
let grade;
if (marks >= 75) grade = "A";
else if (marks >= 50) grade = "B";
else grade = "C";
const day = 2;
let name;
switch (day) {
case 1: name = "Mon"; break;
case 2: name = "Tue"; break;
default: name = "?";
}
const status = marks >= 50 ? "pass" : "fail";
console.log(grade, name, status);switch Statement — if/else and switch pick branches; ternary is a compact expression form of if/else.
How to Explain switch Statement to an Interviewer
When switch Statement?
To branch or repeat Show one small snippet