0
var income = parseInt(prompt('Please enter your income 
   here.'))





switch (income){
   case (income < 9701):
       console.log ('Your tax rate is 10%');
           break;
   case (income > 9700 && income <= 39475):
       console.log('Your tax rate is 12%');
           break;
    case (income > 39475 && income <= 84200):
       console.log('Your tax rate is 22%');
           break;
   case (income > 84200 && income <= 160725):
       console.log('Your tax rate is 24%');
           break;
   case (income > 160725 && income <= 204100):
       console.log('Your tax rate is 32%');
           break;
   case (income > 204100 && income <= 510300):
       console.log('Your tax rate is 35%');
           break;
   case (income >= 510300):
       console.log('Your tax rate is 37%');
           break;
   default:
       console.log('Please enter a valid income')

}

Why does this code keep logging the "default" value to the console? If I put an equals sign in the case, i.e. case (income = 9700) and input 9700 then it logs ('Your tax rate is 10%') When I use greater/less than or equal to operators the code goes to default.

2 Answers2

0

Just like most people said in the comments - you cannot use a switch-statement that way. Please see the more descriptive answer here: Switch statement for greater-than/less-than

If you want to switch your solution to an IF/ELSE logical solution, here is one example of how to format your code with oneliners (ternary operators):

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

var income = parseInt(prompt('Please enter your income here.'))

var currentTaxBracket 
= income < 9701 ? 'Your tax rate is 10%' 
: income > 9700 && income <= 39475 ? 'Your tax rate is 12%'
: income > 39475 && income <= 84200 ? 'Your tax rate is 22%'
: income > 84200 && income <= 160725 ? 'Your tax rate is 24%'
: income > 160725 && income <= 204100 ? 'Your tax rate is 32%'
: income > 160725 && income <= 204100 ? 'Your tax rate is 35%'
: income >= 510300 ? 'Your tax rate is 37%'
: 'Please enter a valid income'

alert(currentTaxBracket)
Salmin Skenderovic
  • 1,750
  • 9
  • 22
0

You could take a function with an early exit approach and check the value from the smallest to greatest and omit not neccessare checks.

function getTaxRate(income) {
    if (income < 9701) return 10;
    if (income <= 39475) return 12;
    if (income <= 84200) return 22;
    if (income <= 160725) return 24;
    if (income <= 204100) return 32;
    if (income <= 510300) return 35;
    return 37;
}

var income = parseInt(prompt('Please enter your income here.')),
    rate = income > 0 && getTaxRate(income);

console.log(rate
    ? `Your tax rate is ${rate}%`
    : 'Please enter a valid income'
);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392