Help for an exercice if else turn to switch

Hello,

I finished the conditional exercises and I wanted to practice a bit by changing an if else block into a switch.
The if else works but I don’t see how to turn it with switch, does anyone have an idea?

thanks.

let applePrice = 1.49;
let orangePrice = 2.23;
let kiwiPrice = 1.29;

if (applePrice > orangePrice){
console.log(‘Buy oranges !’);
}else if(applePrice > kiwiPrice ){
console.log(‘Buy kiwis’);
}else{
console.log(‘Buy apples’);
}

switch (applePrice){
case applePrice > orangePrice:
console.log(‘Buy oranges’);
break;
case applePrice > kiwiPrice:
console.log(‘Buy Kiwis’);
break;
default:
console.log(‘Buy oranges’);
break;
}

Change your:

To:

switch (true) {

and it works as expected.

If the values are set as followed, the outcome is the expected ‘Buy kiwis’

let applePrice = 2;
let orangePrice = 2.23;
let kiwiPrice = 1.29;

switch (true) {
    case (applePrice > orangePrice):
        console.log('Buy oranges');
        break;
    case (applePrice > kiwiPrice):
        console.log('Buy Kiwis');
        break;
    default:
        console.log('Buy oranges');
        break;
    }
1 Like

switch statements are usually only used to check whether something is equal to something else, not greater or less.

example
if (x === 3) {
  console.log("three");
}
else if (x === 4) {
  console.log("four");
}
else {
  console.log("other");
}

is similar to doing

switch(x) {
  case 3:
    console.log("three");
    break;
  case 4:
    console.log("four");
    break;
  default:
    console.log("other");
    break;
}
1 Like

When a case expression is truthy, it matches the switch expression. What is so wrong with that?

I would agree with @janbazant1107978602 and say it’s a matter of convention and readability. Just like the use of a fat arrow function vs function declarations. Because of a discussion with an experienced developer I read somewhere on this forum, I switched from using arrow function for very complex functions to function declarations :slight_smile:

1 Like

yes it works, thank you, and I understood my mistake

Truth be known I’d rather use an object than either switch or if…else. Yes, convention dictates a lot of things in favor of some others.

1 Like

ok, thanks for this information. i was just trying this out for practice