I am learning JavaScript and currently I build simple tip calculator using function and switch statement. Basically, tip 20% of the bill when the bill is less than $50, 15%
This is because you are comparing switch(bill) where bill is number to boolean case: ... where case is if statement. This will always lead to default since any comparison would fail. You need to change switch as switch(!!bill) or simply switch(true)
function simpleTipCalculator(bill){
let tip = 0
switch(!!bill) {
case (bill > 0 && bill < 50):
tip = bill * 0.2
break;
case (bill >= 50 && bill <= 200):
tip = bill * .15
break;
default:
console.log('default');
tip = bill * .1
}
return tip;
}
console.log(simpleTipCalculator(124));
switch case does not work the way you are using it.
switch(test){
case a:
break;
case b:
break;
case c:
break;
}
compares the value of test to the value of a, then b and so on
so in your first code example it compares
124 with the value/output of (bill > 0 && bill < 50) which is false
so you are comparing integers with booleans.
To make ranges work you have to do it like in your second example.
Stackoverflow post I found: https://stackoverflow.com/a/5619997/7584725
When you do
switch(bill){
a case will be fulfilled if the expression that follows it is === to the value of bill. For example, if bill is 124, then switch(bill) would require
case: 124:
tip = bill * .15 // because 124 <= 200
for your program to work as expected. Your code is producing unexpected results because all the cases fail, and it falls through to the default.
The switch(true) works because when you have cases of
case bill > 0 && bill < 50:
this will effectively evaluate to
case true
// block below will run, because `true` is `===` to the expression that was switched against
or
case false:
// block below will not run, because `false` is `!==` to the expression that was switched against
and run the case block accordingly.
switch is not the right tool for the job, IMO - it's confusing and verbose. (It's never the right tool for any programming task in Javascript, I think.) I'd use if/else instead:
const getTip = (bill) => {
if (bill > 0 && bill < 50) {
return bill * 0.2;
} else if (bill >= 50 && bill <= 200) {
return bill * 0.15;
} else {
return bill * 0.1;
}
};
function simpleTipCalculator(bill) {
console.log(getTip(bill));
}
simpleTipCalculator(124)
simpleTipCalculator(48)
simpleTipCalculator(268)