switch
uses ===
to compare the switched expression against every case. For example, if age
is 13, then
switch (age) {
case age < 18:
alert("You are a child");
break;
case age > 18:
alert("You are an adult");
}
evaluates to
switch (13) {
case 13 < 18:
alert("You are a child");
break;
case 13 > 18:
alert("You are an adult");
}
which is
switch (13) {
case true:
alert("You are a child");
break;
case false:
alert("You are an adult");
}
The switched expression, 13
, is not equal to any of the case
s.
You need to logic your way through it - if, when using switch
, your switched expression is not going to be ===
to any of the cases, use switch(true)
, which works if the cases are conditionally true:
switch (true) {
case age < 18:
alert("You are a child");
break;
case age > 18:
alert("You are an adult");
}
when age
is 13
, evaluates to
switch (true) {
case true:
alert("You are a child");
break;
case false:
alert("You are an adult");
}
Now, the switched expression true
is ===
to one of the cases.
Or, even better, just use if
/else
, there are rarely any good times to use switch
IMO:
if (age < 18) {
console.log('You are a child');
} else {
console.log('You are an adult');
}