OnlineCBT Logo OnlineCBT
JavaScript Tutorial
JAVASCRIPT · LESSON 6

Conditional Statements: if, else if, else, and switch

By Ratan Updated: 16 Oct 2026

Control application execution flow using conditional decision branches and switch statements.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

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 score

The 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

  1. Test -1, 0, 39, 40, 59, 60, 79, 80, 100 and 101 in classifyScore.
  2. Test NaN and '80'; the example rejects both.
  3. Add a 'cancel' switch action with its own message.
  4. Explain why putting score>=40 first would classify 90 incorrectly if later branches are intended for higher grades.

हिन्दी संकेत: पहले input की validity, फिर सही क्रम में thresholds जांचें।

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat