Optionality of break in switch-case construct in JavaScript

The break command in the switch-case construct is optional. In the absence of break, after the planned case is executed, all case below it will also be executed.

Let's look at an example:

let num = 1; // let be here the number 1 switch (num) { case 1: console.log(1); // it will work case 2: console.log(2); // and this too case 3: console.log(3); // and this too }

Let's change the value of the variable:

let num = 2; // let be here the number 2 switch (num) { case 1: console.log(1); case 2: console.log(2); // it will work case 3: console.log(3); // and this too }

Let's change the value of the variable:

let num = 3; // let be here the number 3 switch (num) { case 1: console.log(1); case 2: console.log(2); case 3: console.log(3); // it will work }

Sometimes this feature is used when solving problems. See an example:

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

It's more obvious, however, to solve such a problem through if:

let num = 1; let res; if (num == 1 || num == 2) { res = 'a'; } if (num == 3) { res = 'b'; } console.log(res);
enru