1

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.

  • Because you are comparing multiple variables, you should probably just stick with if/else instead of switch. – theusaf May 25 '20 at 05:16
  • Yo, possibly, consider some new answers as the accepted ones that answer the question of how to do the actual switch statement, as the currently accepted one ignores the question, if you find them more helpful (never be aftraid to change the accepted answer from one to a better one! :)) – B''H Bi'ezras -- Boruch Hashem May 25 '20 at 05:41
  • Also might I humbly reccomend a new answer that may have come up https://stackoverflow.com/a/61996412/2016831, you *may* find it useful – B''H Bi'ezras -- Boruch Hashem May 25 '20 at 05:56

5 Answers5

2

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.

Raul Marquez
  • 948
  • 1
  • 17
  • 27
  • nice solution, although it doesn't involve `switch` and `case` like the question asked – B''H Bi'ezras -- Boruch Hashem May 25 '20 at 05:42
  • see this works better but the issue im trying to fix, and I was also trying to fix from the answer I marked was that the cost of traveling to island Hawaii isnt 250, with your solution when I chose Haiwaii, it says cost is 250, but truly the cost of one island is 1350 which is something I cant seem to figure out how to do the math of. – Aria Ghasemi May 25 '20 at 06:06
2

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!!!

  • 1
    after modifying your first bit of code, I got what i needed, THANK YOU!. it took a while i tested every answer given by everyone but yours seemed to hit it on the nail. I just had to modify and add a bit more cases to get my desired out come. much appreciated! – Aria Ghasemi May 25 '20 at 06:30
  • @AriaGhasemi cool glad it all worked out, let me know if anything else comes up or is needed :) – B''H Bi'ezras -- Boruch Hashem May 25 '20 at 06:31
1

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;

}

Abhishek Bhagate
  • 5,583
  • 3
  • 15
  • 32
  • 1
    @bluejayke If you are copying and pasting and getting a syntax error. It is because in this example ```Switch``` and ```Case``` are capitalized. They are not supposed to be. JavaScript is case sensitive and Capital letters are saved for ```Classes``` or ```Constructor Functions``` – Uzair Ashraf May 25 '20 at 05:26
  • @UzairAshraf not copying and pasting, rewrote it, just didn't realize it was exactly checking the boolean values. For example I had the following `switch(1) {case window.test: console.log("testing");break;default:console.log("nothing"))}`, first I tried it without defining "test", then got default, then I tried defining `test` also, but still got default, then I realized that it was checking it exactly, similar to `===`, so I had to change the test case to `case !!window.test` – B''H Bi'ezras -- Boruch Hashem May 25 '20 at 05:30
  • 1
    @UzairAshraf also the statement `switch(1)`, doesn't work in JS, for the reasons mentioned, it has to be `switch(true)`, because in JS `1 !== /*notice the two "="s*/ true` – B''H Bi'ezras -- Boruch Hashem May 25 '20 at 05:32
  • Ah gotcha! That makes sense. – Uzair Ashraf May 25 '20 at 05:37
1

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;
   }

}
E. Shcherbo
  • 1,128
  • 8
  • 15
0

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!

Uzair Ashraf
  • 1,171
  • 8
  • 20