Note that in your case, if anos
has exactly the value 7, would not fall in any of the case
s 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 if
it 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 switch
es 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.
Where you are initiating the years variable?
– Maurício Z.B
@YODA The variable
anos
is the function parameter.– Victor Stafusa