Strict Equality in Switch
You'll learn why switch statements never perform type coercion when matching cases.
The === Under the Hood
When JavaScript evaluates a switch statement, it compares the switch expression against each case value using strict equality (===), not loose equality (==). This means the value and type must match exactly — no automatic type conversion happens.
let value = "5";
switch (value) {
case 5:
console.log("Number five"); // Won't execute
break;
case "5":
console.log("String five"); // This executes
break;
}
Even though "5" == 5 evaluates to true (loose equality coerces types), the switch statement sees "5" and 5 as different because it uses ===.
Why This Matters
This strict behavior protects you from the same type coercion surprises you'd encounter with loose equality. Imagine switching on user input:
let userInput = "0"; // String from a form
switch (userInput) {
case 0:
console.log("Zero"); // Won't match!
break;
default:
console.log("Something else"); // Executes instead
}
Without strict equality, "0" might accidentally match 0, leading to bugs. The switch statement prevents this by design.
The Takeaway
Think of switch as having an invisible === between your expression and every case. This makes switches predictable and type-safe — you always know exactly what will match, with no hidden conversions.
Key Takeaway: Switch statements use strict equality (===) for all case comparisons, preventing type coercion and ensuring only exact type-and-value matches execute.