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 if
s 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
switch
is 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
switch
with Ifs. These are completely different mechanisms when implemented correctly. oswitch
is like agoto
, he goes to thecase
indicated and continued from then on (including in otherscase
s). When you don’t want to continue oncase
next, you use thebreak
. That is, it is the programmer who is using thebreak
to make it look likeif
, which is not always desirable.– Bacco