Choose a branch from validated input
Use if/else when conditions involve ranges or several tests. Use switch when one value selects among discrete cases. Branch order is part of the algorithm: a broad early condition can hide more specific cases below it.
function classifyScore(score) {
if (!Number.isFinite(score) || score < 0 || score > 100) {
return 'Invalid score';
} else if (score >= 80) {
return 'Distinction';
} else if (score >= 60) {
return 'First division';
} else if (score >= 40) {
return 'Pass';
} else {
return 'Needs practice';
}
}
console.log(classifyScore(76)); // First division
console.log(classifyScore(120)); // Invalid scoreThe function expects a Number, not a form's string value. Convert input before calling it. Returning from each branch stops the function; an else-if chain evaluates later conditions only if earlier ones failed.
Switch and fall-through
const action = 'save';
switch (action) {
case 'save':
console.log('Saving draft');
break;
case 'preview':
console.log('Opening preview');
break;
default:
console.log('Unknown action');
}Expected output: Saving draft. Case matching uses strict-equality-style comparison, so the number 1 and string '1' are distinct. Without break or another control transfer, execution continues into subsequent cases. Group cases intentionally when several values share behavior.
Keep conditions readable
A value's truthiness is not always the validation rule. if (score) rejects a valid zero while accepting many nonnumeric strings. A conditional should express the actual requirement. Use braces to make nested branches unambiguous, and avoid a stray semicolon immediately after an if condition.
Boundary practice
- Test -1, 0, 39, 40, 59, 60, 79, 80, 100 and 101 in classifyScore.
- Test NaN and '80'; the example rejects both.
- Add a 'cancel' switch action with its own message.
- Explain why putting score>=40 first would classify 90 incorrectly if later branches are intended for higher grades.
हिन्दी संकेत: पहले input की validity, फिर सही क्रम में thresholds जांचें।