Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function returning undefined value, a bit confused [duplicate]

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.

like image 594
Rojay Arinze Avatar asked Sep 03 '26 03:09

Rojay Arinze


1 Answers

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.

like image 147
Herohtar Avatar answered Sep 05 '26 18:09

Herohtar