Can I include more than one condition in a case of a switch statement like this?

I’m doing the FCC card-counting exercise.

I want to write a switch statement like this (essentially saying “if the number is between x and y”):

switch (card) {
  case >= 2 & <= 6:
  count += 1;
  if (count > 1) {
    return (count + " Bet")}
    return (count + " Hold")
  }

etc… Should it be written like this (with parantheses)?
case >= 2 & <= 6:

Hi
Mind adding a link to the challenge as well?
Also i think it will helps if you visualize things a bit :3
[ 2, 3, 4, 5, 6 ] + 1
[ 7, 8, 9 ] + 0
[ 10, J, Q, K, A ] - 1

I also had a hard time completing this so i sure recommend to check it out:

1 Like

Thanks. I’ll check out that link. This is the challenge: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/counting-cards

I feel like I’m visualizing it ok and my logic makes sense, but it’s still not working…

This is my full code:

var count = 0;

function cc(card) {
  // Only change code below this line
switch (card) {
  case (>= 2 & <= 6):
  count += 1;
  if (count > 1) {
    return (count + " Bet")}
    return (count + " Hold")
  }
  break;
  case (>= 7 & <= 9):
  if (count > 1) {
    return (count + " Bet")}
    return (count + " Hold")
    break;
    case (10 || "J" || "Q" || "K" || "A"):
    count -=;
    if (count > 1) {
    return (count + " Bet")}
    return (count + " Hold")
} 
console.log(cc(5));

Short Guide:

Switch: Based on the value of the variable, each case covers one from a small list of possible values. You should cover each possible case.

If/Else If/Else: Based on a small number of tests, each clause covers a condition or conditions.You want to keep your conditionals streamlined to minimize clauses.

1 Like

Massive hint for you that helped me out
to simplify things you can use the ++ and the – whenever you need to add our decrease something

1 Like

it seems you are not using the switch correctly

check it out:

3 Likes

@camperextraordinaire Thanks. I assumed that each case (in this case card) would function as the value on the left side of the comparison operator. I see my error as my code did not take into account the strings ‘J’, ‘K’, etc…
The Javascript function was provided in the exercise already, how did I mess it up? I checked my closed brackets and they all seemed to have corresponding brackets so I don’t know where I’m messing that up.

Regarding your last point, I see it should be if (count > 0) {

My erroneous code aside, assuming the card values were only numbers, could you let me know if this would function in a switch statement?

switch (card) {
  case (>= 2 & <= 6):
  count += 1;
  if (count > 0) {
    return (count + " Bet")}
    return (count + " Hold")
  }
  break;

Again, my thinking is that the card is functioning (via the case as the value to the left of >=6). Meaning:

switch (card) {
  case ((the card value would be here)>= 2 & (the card value would be here)<= 6)

Thank you

1 Like

wrong syntax for switch, I linked above the documentation on it

this is exactly the same as writing

if (card === (>= 2 & <= 6)) {...}

totally wrong syntax.

2 Likes

Specifically w/r/t the broken logic in the first two lines of your switch:

switch (card) {
  case (>= 2 & <= 6):
    ...

Switch says: take the value in the brackets (switch (card)), and if it matches a case, do the thing in that block.

So card is either a number between 1 and 10 inclusive, or ‘A’, ‘J’, ‘Q’ or ‘K’.

So assume it is 5.

switch (5) {
  case (>= 2 & <= 6):

The case isn’t valid javascript (or any programming language). >= or <= expect a comparison. So 1 <= 2, x >= y, etc, something on both sides. Leaving off one side makes there’s no comparison, it can’t ever work, and you just get a syntax error. So I assume you mean:

switch (card) {
  case (card >= 2 & card <= 6):
  ...

So if card is 5, then 5 >= 2 & 5 <= 6 is 1.

5 is not 1, so that branch does not run. This is because

5 >= 2 & 5 <= 6

is

true & true

is

1 & 1

which is 1 BITWISE_AND 1. Which is 1.

I assume you meant

switch (card) {
  case (card >= 2 && card <= 6):
  ...

So again assuming card is 5, this evaluates to:

switch (5) {
  case (5 >= 2 && 5 <= 6)

Which evaluates to

switch (5) {
  case (true):
  ...

5 does not equal true, so that branch does not run. 5 equals 5, not true.

Edit: you can put logical operators in case statements but you need to remember that they evaluate to true or false. So if you want to do this (and this is not the point of this exercise, this is for future reference) you do not switch on card, you switch on true: if a case evaluates to true, run that branch:

switch (true) {
  case card >= 2 && card <= 6:
    // do stuff
3 Likes

Thank you everyone for your detailed responses! I understand what I was misunderstanding of the switch statement now. Much appreciated!

2 Likes

You got this! :sunny:

1 Like

@mjohnstonee Thanks… Well, I’m getting this (slowly but surely)!

@El_Escandalo we all believe in you!!

2 Likes

@camperextraordinaire Just a quick question on indentation/brackets. Are there any guides to how to properly indent code? I’m not changing the indentation, however it was indented was automatically done.

Also is there any way to disable the autocomplete when I’m coding in FCC? Every time I write an open bracket it automatically includes a closed bracket (which I find annoying). Then I end with multiple closed brackets at the bottom of my code and I need to go through them and erase them.

Thanks

It’s turned on for the app, you can’t turn it off. You can cancel the hints by pressing escape when they pop up, but the bracket autocompletion is always going to happen; I would try to get used to it as it tends to be very helpful once you adjust your typing to take it into account

1 Like

Did you finish it? Im curiouse I restarted mine once more :3
If you still did not want to try and fix it together we can dm one another

1 Like

Thanks. I remember a short while ago trying to do something similar with a switch statement where instead of a simple value, I needed to test various conditions. I tried something similar to what El_Escandalo tried, and even reasoned similarly (that the switch (condition) would provide the left side of the statement and each individual case would be the right-hand side.) After failing, I checked MDN and found that the switch is based on a value not a condition.

However, I have been thinking about your statement that case card >= 2 would evaluate to true or false. It made me realize there was a way to do this kind of switch statement. It might not be the recommended use of the switch statement, but it works. I made a snippet that tests the idea.

function cc(card) {
    console.log(card);
    switch (true) {
        case (card >= 2 && card <= 6):
            console.log("card >= 2 && card <= 6");
            break;
        case (card >= 7 && card <= 9):
            console.log("card >= 7 && card <= 9");
            break;
        default:
            console.log("card is 10, J, Q, K, or A");
    } 
}

cc("A");
cc(2);
cc(3);
cc(4);
cc(5);
cc(6);
cc(7);
cc(8);
cc(9);
cc(10);
cc("J");
cc("Q");
cc("K");

Saw this after I posted my snippet. switch (true) is an interesting use of the switch statement. I wonder how kosher it is. Sure seems to open up some possibilities.

A switch (true) is effectively a mangled if-else statement. I would not recommend using a switch in this way.

Again

Switch: Based on the value of the variable, each case covers one from a small list of possible values. You should cover each possible case.

If/Else If/Else: Based on a small number of tests, each clause covers a condition or conditions.You want to keep your conditionals streamlined to minimize clauses.

Code doesn’t just reach correct answers. It also communicates with future developers and maintainers and facilitates future growth and development. Using a switch in this highly unconventional way to replicate an if-else would decrease readability and maintainability.

That said, @wmoore98, cool work figuring out how it could be done even though it shouldn’t be done in production code.

1 Like

It’s neither uncommon nor unconventional, and whether it’s more or less readable is based entirely on context. switch matches a specific simple value, be that a number or a string or a boolean or whatever, it’s in no way incorrect to match on true.

In cases where there are only a few branches (which is most common) an if/else is better. If the conditions are dissimilar, then if/else is always better as switch is not applicable. But if you have a large number of short similar boolean conditions, it is much clearer to write a switch than if/if else/if else/if else/etc – for one thing everything lines up and it is much easier to scan read. For example a line parser function:

function line (str) {
  switch (true) {
    case /regex1.../.test(str):
      return // thing;
    case /regex2.../.test(str):
      return // thing;
    case /regex3.../.test(str):
      return // thing;
    case /regex4.../.test(str):
      return // thing;
    case /regex5.../.test(str):
      return // thing;
    ...and so on
  }
}

It’s not close to being as powerful as pattern matching (ie a case expression) in ML-based functional languages (or Rust, Scala, Kotlin, Swift, Erlang/Elixir, etc, or C#'s switch). But it’s much closer to it (and produces much cleaner code) than reams of if/else blocks. Note that if the pattern matching proposals make it through the tc39 process this all becomes moot because in general pattern matching produces much cleaner code than multiple if/else’s and also handles the switch(true) use case

1 Like