What is the logic behind the switch case in Javascript?

Asked

Viewed 195 times

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 switch is common to several languages - probably more of a "legacy" of C, and a common "prank" of these languages)

  • 2

    A constantly repeated error on many websites is the comparison of switch with Ifs. These are completely different mechanisms when implemented correctly. o switch is like a goto, he goes to the case indicated and continued from then on (including in others cases). When you don’t want to continue on case next, you use the break. That is, it is the programmer who is using the break to make it look like if, which is not always desirable.

2 answers

8


It is a characteristic of the language each case may have break. This is how language was drawn. When a break the switch is interrupted.

The case is a label, acts as a pointer to the statement where will run code for the specific case. In Javascript Labels do not block the code, so it is possible to run code within several cells up to one break stop them.

Having said that, the absence of break in the switch is not syntax error but causes undesirable behavior. As stated in MDN: _"the absence of break will make the script run the "case" code in "case" until you find a break or the switch break up.

The optional break statement Associated with each case label Ensures that the program breaks out of switch Once the Matched statement is executed and continues Execution at the statement following switch. If break is omitted, the program continues Execution at the next statement in the switch statement.

Even in the case of the last case that technically would not need a break, it is preferable to have always for consistency and to avoid aberrant behaviors difficult to debug.

const permissao = 'estagiário';

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;
}

  • 4

    "It is a feature of the language each case have its break" - This is incorrect. The break is optional. It should only be used when there is no interest in continuing on case next. There are many situations where the cascade is desirable (the most common is you attend several cases with the same code, but it is not restricted to this)

  • @Bacco agree, what I mean by that is that each case may associate a break. In the reinforcement response that is optional but cannot (at least has no effect) have 2 break for the same case.

  • It has no effect only because it never reaches the 2nd break, after all any break causes exit. The break there is mechanism of switch, not of case. The case is practically a jump-list to determine the entry point, that’s all.

  • 1

    @Bacco okay, I see what you meant by how incorrect: or is I associate that the break exists as a "tag to close the case". Yes, in that sense you are right and it is incorrect. I will clarify.

  • 4

    Complementing, a very common example (I used strings only to illustrate) where it is desirable not to use break: case 'UP': case 'LEFT': case 'SHIFT TAB': fichaAnterior(); break; - that is, any of the keys must perform fichaAnterior(), does not have to repeat code. The cascade is not side effect, it is a desirable mechanism. It is only side effect when using the switch in place of if, but again, it is a programmer’s option, not the philosophy of the Construct itself.

  • @Bacco, would it be correct to say that break is a "do" switch mechanism? It can be used in loop and other structures as well.

  • 2

    @Spencermelo in the current context is switch mechanism, not case. In other contexts it also has break, but is not relevant to the point in question. The fact here is that the structure he’s breaking is the switch. Similarly, a while with if (...) { break } the break is from while, and not of if.

  • Right, so I can assume that without some label, it’s going to be from the loop or switch structure "above"?

  • 2

    @Spencermelo just the opposite. If it were the case, that has the label, you could assume this, but as is the switch and the switch is present, it will come out of the switch. Not that it changes the situation, but to be honest, I have not even tried empty switch to see if the JS accepts. Capable that it is not even possible.

  • Okay, thank you!

Show 5 more comments

2

That’s how it works:

  1. The commutator expression is evaluated once.
  2. The expression value is compared with the values of each case.
  3. If there is a match, the associated code block will be executed.
  4. If there is no match, the default code block is executed.

If you notice, in point 2. it executes all the blocks. Hence it is necessary to break, to ensure that only executes the desired.

Source:https://www.w3schools.com/js/js_switch.asp

  • You know why the absence of break causes the case following validate true?

  • Yes, thank you for the most complete reply! It will help the Yoyo

  • 3

    Switch Case is equivalent to goto, is not like a if. There is no such comparison with each case, only the correspondence is located and the code follows the flow from then on.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.