5
I started my studies in Javascript and had contact with the switch, following example:
let permissao;
switch (permissao){
default:
console.log('sem acesso');
break;
case 'estagiário':
console.log('acesso limitado');
break;
case 'contratado':
console.log('acesso pleno');
break;
case 'gerente':
console.log('acesso irrestrito');
break;
}
From what I understand, the switch acts as a chain of ifs simplified. So why is it necessary to use the break?
I think that if the cases are execution instructions for a specific situation, if the situation does not comply with the case, should not be executed, such as a if. But if I take the breaks, it runs as if all situations were true, which is not true. What is the logic behind it?
Related: How the switch works behind the scenes? | Break and Continue on Switch | The last instruction of a switch needs 'break'? (although not specifically about Javascript, this behavior of
switchis common to several languages - probably more of a "legacy" of C, and a common "prank" of these languages)– hkotsubo
A constantly repeated error on many websites is the comparison of
switchwith Ifs. These are completely different mechanisms when implemented correctly. oswitchis like agoto, he goes to thecaseindicated and continued from then on (including in otherscases). When you don’t want to continue oncasenext, you use thebreak. That is, it is the programmer who is using thebreakto make it look likeif, which is not always desirable.– Bacco