Search code examples
javascriptarraysfunctionswitch-statementreturn

Returning a value from switch statement


I'm new to web development (JS) and I know there are many topics matching the title of mine, but no similar questions were answered, or maybe because I'm newbie, couldn't find.

In the code below I wanted my function and switch statements, to retrieve values from the arrays (bills) and in order to calculate new value, which to be assigned into a new non-existing place into the array tips. As a final result I want the function to return tips array with the value, depending on the case.

I know another way for solving this, anyway I was wondering whats wrong here, because that idea for solving it first came to my mind, and I thought it would work.

Here is my code:

var tips = [];
var bills = [124, 48, 264];

function tipCalc(bills, tips){
 switch(bills){
    case bills < 50:
      tips[0] = bills[1] * 0.2;
      break;

    case bills > 50:
      tips[1] = bills[0] * 0.5;
      break;

    default:
      console.log('no tips left.');
  }
  return tips;
}

tips = tipCalc(bills[0]);
console.log(tips);

enter code here

Solution

  • Let's break this code down a bit and talk about what it's doing

    var tips = [];
    var bills = [124, 48, 264];
    

    This part is declaring two variables in the global scope, which will both be accessible by any functions for both reading and writing (important - Google JS closures).

    function tipCalc(bills, tips){
     switch(bills){
    

    You have now started a function which calls a switch to evaluate the value of bills. Because you are passing in bills[0], it will be evaluating bills[0] (124). It also accepts a second parameter called tips, which is undefined because no second argument is passed in when the function is called.

    case bills < 50:
      tips[0] = bills[1] * 0.2;
      break;
    

    This part is broken. If it was changed to an if statement, it would evaluate to false.

    case bills > 50:
      tips[1] = bills[0] * 0.5;
      break;
    

    Also broken. If changed to if statement, it would evaluate to true and be executed, but it would be performing an operation on undefined. If you didn't h have a second param also named tips, then you would be setting the global tips to 62.

        default:
          console.log('no tips left.');
      }
    

    This is the part that should currently be executed because it is the only one that can be true with the other two cases being structured incorrectly.

      return tips;
    }
    

    Will return undefined because tips (within the scope of the function itself) began as undefined and has not been altered.

      tips = tipCalc(bills[0]);
      console.log(tips);
      enter code here
    

    Breaks the whole program, should be a comment with // at the beginning.