I’ve been trying to create a code in JavaScript using the switch statement to calculate the income tax for Brazilian residents. I know I can do that using if-else, which I already did and worked perfectly. However, I want to enhance my skills, and so I’m trying the same income tax table now using switch.
The code has been created, however no matter what number I use as salary, the result always goes straight to the default block, executing that very last string piece.
Could anyone please advise on where my mistake is?
console.log(`INCOME TAX TABLE 2023 - BRAZIL`);
const salary = 2000;
switch (salary) {
case (salary < 1904):
console.log(`You're exempt from paying taxes this year`);
break;
case (salary >= 1904 && salary < 2827):
console.log(`You fell in the 7.5% category. The amount of income tax you must pay is ${salary * 0.075}`);
break;
case (salary >= 2827 && salary < 3751):
console.log(`You fell in the 15% category. The amount of income tax you must pay is ${salary * 0.15}`);
break;
case (salary >= 3751 && salary < 4665):
console.log(`You fell in the 22.5% category. The amount of income tax you must pay is ${salary * 0.225}`);
break;
default:
console.log(`You fell in the 27.5% category. The amount of income tax you must pay is ${salary * 0.275}`);
}
3
Answers
You can’t use
switch
statements in this way. You’re giving each case a boolean expression which resolves totrue
orfalse
. Neither of those two values will ever be equal to2000
(the value ofsalary
) so no case is matched and the default is hit.You can’t but true/false statement in a switch case. Switch case is meant to be used if you have a variable with multiple answer. Say the answer can be 1, 2, 3, or 4. You can put multiple segment of int in that range. For that purpose, you might want to stick to if else statement.
The switch expression is compared with case expressions.
Here the case expressions are boolean (true/false).
So in switch use the true, to get the case with the truth.