Note that in your case, if anos
is exactly 7, it would not fall into any of case
s or default
. I think the condition of default
should be >= 7
instead of > 7
.
The block switch
serves to relate each case
to exactly one value. You can not map a case
to a range of default values. There is no such thing as putting an expression after case
or default
just like you were trying to do. This is not how 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 switch
to run at intervals by putting expressions in cases
and true
in 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 an interpreted language with poor typing. In other languages that also have switch
but are compiled, such as C, C ++, Objective-C, C #, and Java, that does not work.
However, if you do something like this, maybe giving up switch
and using if
s 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 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 (my own), the switch
es are horrible language constructions that should not even exist. In 99% of the time a switch
is used, there is something else that could be used instead that would be much better or at least as good as.