**switch** compares a value against multiple cases using strict equality (`===`). Without `break`, execution **falls through** to the next case. This can be intentional (grouping cases) or accidental (a common bug). Always include a `default` clause.
1Understanding switch Statement
switch compares a value against multiple cases using strict equality (===). Without break, execution falls through to the next case. This can be intentional (grouping cases) or accidental (a common bug). Always include a default clause.
switch uses === internally, so switch('1') will NOT match case 1.
const day = 3;
let name;
switch (day) {
case 1: name = 'Monday'; break;
case 2: name = 'Tuesday'; break;
case 3: name = 'Wednesday'; break;
case 4: name = 'Thursday'; break;
case 5: name = 'Friday'; break;
default: name = 'Weekend';
}
console.log(name);2Practical Example
Here is a real-world application of switch Statement showing how it is used in production JavaScript code.
// Intentional fall-through grouping
const type = 'jpg';
let category;
switch (type) {
case 'jpg':
case 'png':
case 'gif': category = 'image'; break;
case 'mp4': category = 'video'; break;
default: category = 'other';
}
console.log(category); // 'image'3Best Practices
Follow these guidelines when working with switch Statement:
1. Always add break (unless intentional fall-through)
2. Always include a default case
3. For complex logic, prefer if/else or object maps
Tip: switch uses === internally, so switch('1') will NOT match case 1.
const day = 3;
let name;
switch (day) {
case 1: name = 'Monday'; break;
case 2: name = 'Tuesday'; break;
case 3: name = 'Wednesday'; break;
case 4: name = 'Thursday'; break;
case 5: name = 'Friday'; break;
default: name = 'Weekend';
}
console.log(name);