I'm trying to solve a problem for a course I'm currently doing, but I've been stuck on why my code returns undefined for about an hour now.
I've switched a few things around, added brackets to make sure things are in order, idk what else to try.
var bills = [124, 48, 268];
function tipsCalculator(bill) {
switch (bill) {
case bill < 50:
return (bill * (20 / 100));
case bill >= 50 && bill <= 200:
return (bill * (15 / 100));
case bill > 200:
return (bill * (10 / 100));
}
}
var testing = tipsCalculator(bills[0]);
console.log(testing);
I expect it to return the calculation of the 124 * whichever case that value fits.
That's not a valid use of switch. You will have to use if statements:
var bills = [124, 48, 268];
function tipsCalculator(bill) {
if (bill < 50)
return (bill * (20 / 100));
if (bill >= 50 && bill <= 200)
return (bill * (15 / 100));
if (bill > 200)
return (bill * (10 / 100));
}
var testing = tipsCalculator(bills[0]);
console.log(testing);
The reason it doesn't work is because expressions like bill < 50 evaluate to a boolean value -- either true or false. So when your code executes tipsCalculator(bills[0]) the function looks like this:
function tipsCalculator(124) { // bills[0] == 124
switch (124) {
case false: // 124 > 50 == false
return (124 * (20 / 100));
case true: // 124 >= 50 == true, 124 <= 200 == true, thus true && true == true
return (124 * (15 / 100));
case false: // 124 > 200 == false
return (124 * (10 / 100));
}
}
As you can see, the only cases are true and false, but 124 is neither of those, so your function completes without entering any of the cases and since no return statements are executed, the return value is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With