Doubt switch structure Javascript

Asked

Viewed 71 times

-3

In this example.

switch(numero {
          case '0':
          case '1':
          case '2':
          case '3':
          case '4':
          case '5':
          case '6':
          case '7':
          case '8':
          case '9': console.log('Case 9');
          break;

The instruction is falling in case 9, when the number = '2', I know this happens because the break instruction was not used in case '2', but why this happens, since '2' is different from '9'?

  • Switch is cascade effect by default in javascript, some languages are not. So it’s not a code error, it’s just standard behavior that you have to adapt in each language. It’s like English and Portuguese, things change order and there’s nothing wrong with that, but if we want to do it right, we have to learn and execute it the way each of us.

2 answers

0

Paulo, the switch has exactly this behavior, when the break instruction is omitted, so that the switch finds a valid condition, it will enter the other, even if the conditions are not met... It follows to the end or even find a break instruction.

Run the example below, and you’ll see that as FOR runs, the amount of information decreases:

for (let numero = 0; numero < 10; numero++ ) {
    switch (numero) {
        case 0: console.log('Case 0');
        case 1: console.log('Case 1');
        case 2: console.log('Case 2');
        case 3: console.log('Case 3');
        case 4: console.log('Case 4');
        case 5: console.log('Case 5');
        case 6: console.log('Case 6');
        case 7: console.log('Case 7');
        case 8: console.log('Case 8');
        case 9: console.log('Case 9');
        break;
    }
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch


0

This happens because if you put two or more case without a break it would be like "if it’s 0, or 1, or 2, or 3...." that is, like a sequence of values with "or". As if it were a command if thus:

if (numero==0 || numero==1...)

If you want to separate each option, add a command for each one:

switch(numero {
          case '0': 
               console.log('Case 0');
               break;
          case '1': 
               console.log('Case 1');
               break;
          ... etc ...
  • 1

    In that case, if you enter numero = '0', all the console.log will be executed. It did not seem to me to be the behavior that I wanted to put.

  • truth @Andersoncarloswoss , missed break :( corrected

Browser other questions tagged

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