Is it possible to have the switch statements perform other comparisons besides a direct equal. As shown in this example it compares if the string = papaya essentially. Is there a was to us Switch and see if it’s >, >=, !=, and so on?
let groceryItem = ‘papaya’;
switch (groceryItem) {
case ‘tomato’:
console.log(‘Tomatoes are $0.49’);
break;
case ‘lime’:
console.log(‘Limes are $1.49’);
break;
case ‘papaya’:
console.log(‘Papayas are $1.29’);
break;
default:
console.log(‘Invalid item’);
break;
}
And to add another question what exactly is that input doing? In the example it showed it with having the variable so why does adding a boolean change this?
In the example you posted, the variable groceryItem has been assigned the string value 'papaya'.
The cases such as 'tomato', 'lime', 'papaya' are also strings. Therefore, using groceryItem as the switch expression is an appropriate choice.
switch (groceryItem) {
When expressions involve comparisons (using comparison operators such as ==, !=, >, >=, <, <= ), then evaluation of these expressions results in boolean values (true/false).
So, expressions such as (price >= 40) or (price < 0) etc. are going to result in a true/false answer. This means that the cases are going to be booleans. Hence, the choice of a boolean as the switch expression in
switch (true) {
In your example, the cases had string values. Hence the choice of a string as the switch expression.
If the cases had number values, then the switch expression should also be a number.
If we want the cases to be comparisons, then the cases will be boolean values. Accordingly, the switch expression should be a boolean.