switch & case Keywords

Use switch to select one of many branches based on a single expression.
Each case is a label to match; use break to stop execution, and default as the fallback when no case matches.


Syntax

switch (expression) {
  case value1:
    // statements
    break;            // usually stop here
  case value2:
    // statements
    break;
  default:
    // fallback
}

// Grouping multiple cases
switch (x) {
  case 1:
  case 2:
  case 3:
    // handle 1,2,3
    break;
  default:
    // ...
}

// Placing default earlier (falls through if no break)
switch (code) {
  default:
    console.log("Unknown");
    // no break -> falls through
  case "A":
    console.log("Handled A");
    break;
}

Examples

// ১) গ্রেড মেসেজ
let গ্রেড = "B";

বিকল্প (গ্রেড) {
  অবস্থা "A":
    কনসোল.লগ("দারুণ!");
    থামুন;
  অবস্থা "B":
    কনসোল.লগ("ভালো কাজ!");
    থামুন;
  অবস্থা "C":
    কনসোল.সতর্ক("গড় মান");
    থামুন;
  অন্যথায়:
    কনসোল.ত্রুটি("ভুল গ্রেড");
}

// ২) সপ্তাহের দিন গ্রুপিং
const দিন = 6;
বিকল্প (দিন) {
  অবস্থা 1:
  অবস্থা 2:
  অবস্থা 3:
  অবস্থা 4:
  অবস্থা 5:
    ছাপাও("কর্মদিবস");
    থামুন;
  অবস্থা 6:
  অবস্থা 7:
    দেখাও("সপ্তাহান্ত");
    থামুন;
  অন্যথায়:
    লিখো("অজানা দিন");
}

// ৩) রেঞ্জ‑চেক: বিকল্প (true) কৌশল
const n = 10;
বিকল্প (true) {
  অবস্থা n < 0:
    কনসোল.সতর্ক("ঋণাত্মক");
    থামুন;
  অবস্থা n === 0:
    কনসোল.লগ("শূন্য");
    থামুন;
  অবস্থা n > 0 && n % 2 === 0:
    কনসোল.লগ("ধনাত্মক জোড়");
    থামুন;
  অন্যথায়:
    কনসোল.লগ("ধনাত্মক বিজোড়");
}

Notes

  • Put break after each case unless you intentionally want fall‑through.
  • Only one default per switch; it can appear anywhere in the block.
  • Use a switch (true) pattern to express range logic succinctly, otherwise prefer if...else for complex predicates.
  • For simple value-to-result mapping, an object map can be faster and more readable than a long switch.