Doubt with switch in Javascript

Asked

Viewed 1,092 times

0

I’m doing a Javascript course, and I need to do an exercise with the statement "Write a function that given a total of years of study returns how experienced the user is."

My code:

function experiencia(anos) {
  switch (anos) {
    case 1:
      anos <= 1
      return 'Iniciante'
    case 2:
      anos > 1 && anos <= 3
      return 'Intermediário'
    case 3:
      anos >= 4 && anos <= 6
      return 'Avançado'
    default:
      anos > 7
      return 'Jedi'
  }
}

var anosEstudo = 3;
console.log(experiencia(anosEstudo));

However, it printa in the 'Advanced' console. It should be 'Intermediate'. Where’s the bug with that code?

  • Where you are initiating the years variable?

  • @YODA The variable anos is the function parameter.

4 answers

6

Note that in your case, if anos has exactly the value 7, would not fall in any of the cases and nor in the default. I think the condition of default should be >= 7 instead of > 7.

The block switch serve to relate each case with exactly a single value. You can’t map a case for a range of values in this way. There is no such thing as putting an expression after the case or the default as you were trying to do. That’s not how the switch works.

Here is a valid example of switch. Note that each case maps exactly one value:

function experiencia(anos) {
    if (anos < 0) return 'Impossível';
    switch (anos) {
        case 0:
        case 1:
            return 'Iniciante';
        case 2:
        case 3:
            return 'Intermediário';
        case 4:
        case 5:
        case 6:
            return 'Avançado';
        default:
            return 'Jedi';
    }
}

for (var i = -2; i <= 10; i++) {
    document.write(i + " anos: " + experiencia(i) + ".<br>");
}

But there is a trick that can be done to force the switch working at intervals when placing expressions in cases and true in the switch:

function experiencia(anos) {
    switch (true) {
        case anos >= 0 && anos <= 1:
            return 'Iniciante';
        case anos > 1 && anos <= 3:
            return 'Intermediário';
        case anos >= 4 && anos <= 6:
            return 'Avançado';
        case anos >= 7:
            return 'Jedi';
        default:
            return 'Impossível';
    }
}

for (var i = -2; i <= 10; i++) {
    document.write(i + " anos: " + experiencia(i) + ".<br>");
}

This works because Javascript is a weak typed language. In other languages that also have the switch but which are compiled, such as C, C++, Objective-C, C# and Java, so it doesn’t work.

However, if you’re going to do such a thing, maybe give up the switch and use ifit would be easier:

function experiencia(anos) {
    if (anos < 0) return 'Impossível';
    if (anos <= 1) return 'Iniciante';
    if (anos <= 3) return 'Intermediário';
    if (anos <= 6) return 'Avançado';
    return 'Jedi';
}

for (var i = -2; i <= 10; i++) {
    document.write(i + " anos: " + experiencia(i) + ".<br>");
}

Or else you could use the ternary operator:

function experiencia(anos) {
    return anos < 0 ? 'Impossível'
            : anos <= 1 ? 'Iniciante'
            : anos <= 3 ? 'Intermediário'
            : anos <= 6 ? 'Avançado'
            : 'Jedi';
}

for (var i = -2; i <= 10; i++) {
    document.write(i + " anos: " + experiencia(i) + ".<br>");
}

In the opinion of many people (including me), the switches are hideous language constructions that should not even exist. At 99% of the times switch is used, there is something else that could be used in its place that would be much better or at least as good as.

4


Summarizing a little the answer of Sam, the most indicated there would be the use of a block if-else in place of switch, because then you already make the return according to the value of a condition already tested.

function experiencia(anos) {
  if(anos == 0 || anos == 1){
    return 'Iniciante';
  } else if(anos > 1 && anos <= 3){
    return 'Intermediário';
  } else if(anos >= 4 && anos <= 6){
    return 'Avançado';
  } else if(anos > 7) {
    return 'Jedi';
  } else {
    return 'Impossível';  // caso digite nº negativos
  }
}

var anosEstudo = -10;
console.log(experiencia(anosEstudo));

  • 1

    Leandrade, thank you! That’s exactly what I needed. I spoke to a friend who knows a lot about javascript and he told me that the switch would not need to be used in this case. Indicated to do exactly as you said.

  • Opa Hardel, but that’s right expensive, programming is just like that, especially when one is starting in a language. It is trying, erring and learning. Javascript is top man, good studies.

2

You sent to the switch the value 3 by the variable anos. With this you will access the case 3.

Soon the return 'Avançado' will be the only answer. The code in case 2 will never be accessed because the value passed to switch was not 2. In addition to the "comparisons" made within each case are ignored because they say nothing, are not inside a if, which would be the method for comparing values.

And even if you put all the comparisons inside one if, only that of case 3 will be accessed, and returned Undefined because the variable anos (3) would not fit the condition >= 4 && anos <= 6.

In short, when sending the value 3 to the switch, only the block case 3 will be accessed.

-2

    <script>

        function experiencia(anos) {


            if (anosEstudo >= 0 && anos <= 1) {

            console.log('Iniciante');

            } else if (anosEstudo <=3) {

                console.log('Intermediário');

            } else if (anosEstudo <= 6) {

                console.log('Avançado');

            } else if (anosEstudo >= 7) {

                console.log('Jedi Master');

            } else {

                console.log('Impossível')

            }

        }


        var anosEstudo = 7;
        experiencia(anosEstudo);

        // De 0-1 ano: Iniciante
        // De 1-3 anos: Intermediário
        // De 3-6 anos: Avançado
        // De 7 acima: Jedi Master
        // Comenta o que acharam do meu código, eu estou comecando
    </script>

Browser other questions tagged

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