Break-ի ոչ պարտադիր լինելը JavaScript-ի switch-case կառուցվածքում

break հրամանը switch-case կառուցվածքում պարտադիր չէ: Եթե break չկա նախատեսված case-ի կատարումից հետո, կկատարվեն նաև դրանից ներքև գտնվող բոլոր case-երը:

Դիտարկենք օրինակով.

javascriptlet num = 1; // ենթադրենք այստեղ թիվը 1 է

switch (num) {
  case 1:
    console.log(1); // կաշխատի սա
  case 2:
    console.log(2); // կաշխատի նաև սա
  case 3:
    console.log(3); // կաշխատի նաև սա
}

Փոխենք փոփոխականի արժեքը.

javascriptlet num = 2; // ենթադրենք այստեղ թիվը 2 է

switch (num) {
  case 1:
    console.log(1);
  case 2:
    console.log(2); // կաշխատի սա
  case 3:
    console.log(3); // կաշխատի նաև սա
}

Փոխենք փոփոխականի արժեքը.

javascriptlet num = 3; // ենթադրենք այստեղ թիվը 3 է

switch (num) {
  case 1:
    console.log(1);
  case 2:
    console.log(2);
  case 3:
    console.log(3); // կաշխատի սա
}

Երբեմն այս առանձնահատկությունն օգտագործում են, առաջադրանքներ լուծելիս: Նայեք օրինակ.

javascriptlet num = 1;
let res;

switch (num) {
  case 1:
  case 2:
    res = 'a';
  break;
  case 3:
    res = 'b';
  break;
}

console.log(res);

Սակայն, ավելի ակնհայտ է լուծել նմանատիպ առաջադրանք if-ի միջոցով.

javascriptlet num = 1;
let res;

if (num == 1 || num == 2) {
  res = 'a';
}

if (num == 3) {
  res = 'b';
}

console.log(res);