why I get Different result in switch statements

后端 未结 3 824
一个人的身影
一个人的身影 2021-01-15 14:39

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%

3条回答
  •  自闭症患者
    2021-01-15 15:12

    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)

提交回复
热议问题