Aria Ghasemi
Aria Ghasemi

Reputation: 35

How do I turn these If else statements into Switch statements

so I have a simple function to see what is checked in the checkboxes, and then spew out the prices. Im trying to make it so i have every possible combination possible as "If" statements so what ever the user chooses, the right price will pop up. I was just wondering How I can turn this code into switch statements to make it for efficient. and if theres anything else thats inefficient I should fix, I would love feedback, this is my first week using JS for a school project.

    <!DOCTYPE html>
<html>

<head>
<script>
function testFunc() {
  cost = 0;
  var isOne = document.getElementById('Maui').checked;
  var isTwo = document.getElementById('Oahu').checked;
  var isThree = document.getElementById('Hawaii').checked;


  if(isOne) {
    cost += 1350
  }
  if(isOne && isTwo) {
    cost = 1850
  }
  if(isOne && isTwo && IsThree) {
    cost = 2100
  }
  else{
    cost = 1350
}
  if(isTwo){
    cost += 0
  }

  document.getElementById('cost').innerHTML = cost;
}

</script>
</head>

<body>

<h2>Chose Islands For Package/h2>

<form>
  <input type="checkbox" id="Maui">

  <label>Maui</label><br>

  <input type="checkbox" id="Oahu">

  <label>Oahu</label><br>

  <input type="checkbox" id="Hawaii">

  <label>Hawaii</label><br>


</form>

 <button onclick="testFunc()">Price </button>

 <p id="cost"> </p>

</body>
</html>

EDIT: sorry I guess I didnt clarify, the cost of traveling to one island is 1350, no matter what island. I think What I am trying to do is too complicated for simple JS code. for exmaple if i chose hawaii, itll be 1350, if i chose two islands itll be 1850, but if its only one island again such as Ohau itll be 1350 again. I was thinking of doing Arrays and/or writing if/else statemnts for each possible variation since switch statements seem to not be the best option for this.

Upvotes: 1

Views: 109

Answers (5)

Switch statements are used to check if one value (or variable) is equal to any one of a subset of other values.

For example, if the value of var string has a case of being equal to foo or a case of bar etc. In this case there are multiple variables being checked, so the simple meaning of a switch statement wouldn't fit.

However deep down every boolean is essentially true or false, so you could instead switch the case of another boolean variable, to check if it is equal to any of the others.

Also keep in mind that with switch statements, the function switch checks the argument entered into it exactly, similar to ===, with each of the cases.

So instead of checking one variable to be a boolean value for many, like in if statements, you could do the reverse, and check the many variables against the argument entered into switch, namely, "true" (the result of all boolean values).

Keep in mind though that when checking boolean values, you cannot use switch(1), because in JavaScript 1 !== true, even though 1 == 2 (difference between 3 equal signs (including ! and 2, for more info on the differences, and consequentially, what you can compare the switch cases with, see Which equals operator (== vs ===) should be used in JavaScript comparisons?).

So you could do, for example:

<!DOCTYPE html>
<html>

<head>
<script>
function testFunc() {
  cost = 0;
  var isOne = document.getElementById('Maui').checked;
  var isTwo = document.getElementById('Oahu').checked;
  var isThree = document.getElementById('Hawaii').checked;


  switch(true) {
    case isOne && isTwo && isThree: 
      cost = 2100;
      break;
    case isOne && isTwo:
      cost = 1850;
      break;
    case isTwo && isThree:
      cost = (2100 - 1350);
      break;
    case isOne: 
      cost = 1350;
      break;
    case isTwo:
      cost = (1850 - 1350 /*based on earlier*/)
      break;
    case isThree:
      cost = 2100 - 1850 //based on earlier
      break;
    default: cost = 0
  }
  

  document.getElementById('cost').innerHTML = cost;
}

</script>
</head>

<body>

<h2>Chose Islands For Package/h2>

<form>
  <input type="checkbox" id="Maui">

  <label>Maui</label><br>

  <input type="checkbox" id="Oahu">

  <label>Oahu</label><br>

  <input type="checkbox" id="Hawaii">

  <label>Hawaii</label><br>


</form>

 <button onclick="testFunc()">Price </button>

 <p id="cost"> </p>

</body>
</html>

Also notice how the cases which check more than one value are first in the switch/case, because the way it works is it checks each case, and the first one that is true is returned.

Also I added one additional check case that wasn't present before, namely case isTwo && isThree.

But BTW, if you just want to calculate the total price for each place, a much more efficient way is to simply make a map object for name to price value, and loop through all the cases, check its price value, and add it to the cost, like this:

<!DOCTYPE html>
<html>

<head>
<script>
function testFunc() {
  cost = 0;
  var map = {
    Maui: 1350,
    Oahu: 500,
    Hawaii: 250
  };
  
  Array.apply(0, myForm.elements)
  .forEach(x => {
    if(x.checked) {
      var cur = map[x.id]
      if(cur) cost += cur;
    }
  });

  document.getElementById('cost').innerHTML = cost;
}

</script>
</head>

<body>

<h2>Chose Islands For Package/h2>

<form id=myForm>
  <input type="checkbox" id="Maui">

  <label>Maui</label><br>

  <input type="checkbox" id="Oahu">

  <label>Oahu</label><br>

  <input type="checkbox" id="Hawaii">

  <label>Hawaii</label><br>


</form>

 <button onclick="testFunc()">Price </button>

 <p id="cost"> </p>

</body>
</html>

Because the current model for which this is being done requires an N! amount of case checks, with N representing the total cases you have.

So for example if you had 10 options to choose from, you would have to manually write out 10!, or 3,628,800 individual case checks!!!

Upvotes: 2

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5786

The below code would do:

switch(true){
     case isOne:
            cost += 1350;
            break;
     case isOne&&isTwo:
            cost += 1850;
            break;
     case isOne&&isTwo&&isThree:
            cost += 2100;
            break;
     default:
            cost=1350;

}

Upvotes: 1

Raul Marquez
Raul Marquez

Reputation: 1116

I would change your testFunc function to this:

function testFunc() {
    var total = 0;
    var maui = document.getElementById('Maui');
    var oahu = document.getElementById('Oahu');
    var hawaii = document.getElementById('Hawaii');

    total = (maui.checked ? 1350 : 0) + 
            (oahu.checked ? 500 : 0) + 
            (hawaii.checked ? 250 : 0);

    document.getElementById('cost').innerHTML = total;
}

EDIT: I didn't use a switch statement for no other reason than you wanting efficiency overall.

Looking at the other answers, including the accepted one, I think they inherited a mistake in summing the prices, there's no case for maui + hawaii.

The solution I provided works for any combination.

Upvotes: 2

javascwipt
javascwipt

Reputation: 1178

Well for starters, you always want to declare your new variables with the var keyword. If you don't you create something called auto-global variables. Which can create unpredictable bugs later on with a bigger code base.

Secondly, using a switch case statement isn't really more efficient. I'd recommend sticking to if/else statements. Also if I am understanding your code properly you are probably trying to adjust your price if certain things are checked. Might just be easier to test each variable and just add to the cost as you go

var cost = 0;
if(isOne) {
 cost += 1350
}
if(isTwo) {
 cost += 1850
}
if(isThree) {
 cost +=2100
}

This way it will always start with zero, and if none of the conditions resolve to true, then cost wont change from zero.

Hope this helps!

Upvotes: 0

E. Shcherbo
E. Shcherbo

Reputation: 1148

Why do you think that those combinations if and else statement make your core ineficcient? I would suggest you to extract a method for calculate cost, so the intention of the code will be more clear:

function testFunc() {
     var isMaui = document.getElementById('Maui').checked;
     var isOahu = document.getElementById('Oahu').checked;
     var isHawaii = document.getElementById('Hawaii').checked;

     document.getElementById('cost').innerHTML = calculateCost(isMaui, isOahu, isHawaii);
}

function calculateCost(isMaui, isOahu, isHawaii) {
   if(isMaui && isOahu && isHawaii) {
       return 2100;
   } else if (isMaui && isOahu) {
       return 1850;
   } else if (isMaui) {
       return 1350;
   } else {
       return 1350;
   }

}

Upvotes: 1

Related Questions