Search code examples
javascriptconditional-statements

Basic JavaScript: Counting Cards - Card Counting Function with Strings


The card function has been explained multiple times, and I understand it. For those who do not know it: my function receives a card parameter, which can be a number or a string. I then increment or decrement the global count variable according to the card's value 2,3,4,5,6 increments, 7,8,9 keeps it at 0, while 10, J, Q, K, A decrements it. My function then returns a string with the current count and the string "Bet" if the count is positive, or "Hold" if it is negative.

So I understand how the function is done, and FreeCodeCamp accepted my solution as technically it meets their conditions. But have a question regarding this function:

var count = 0;

function cc(card) {
  if (card >= 2 && card <= 6) {
    count++;
  } else if (card >= 7 && card <= 9) {
    count += 0;
  } else {
    count--;
  }

  if (count <= 0) {
    return count + " Hold";
  } else {
    return count + " Bet";
  }
}

console.log(cc(2));
console.log(cc(3));
console.log(cc(7));
console.log(cc('K'));
console.log(cc('A'));

As I can see, the first condition is fairly simple and easy to define, so is the else if. In the third case, there are both numbers and strings involved. Does this not mean that when I put ANY string into cc, it will decrement? As anything that is not between 2 and 6, or 7 and 9, will automatically decrement? Even if the user inputs something that is not a card or is not a value from the list?

I understand that there is a list of predefined card values and names, but nevertheless, is there any better way to condition my statement to make sure that my condition will ONLY run IF the card is either 10, J, Q, K or A, and not any other value?


Solution

  • You can change your current else, to return and error message or just return immediately in case of the input being a non-valid card, and add another else-if to check for 10 through Ace:

    if (card >= 2 && card <= 6) {
        count++;
      } else if (card>=7 && card <=9) {
        count+= 0;
      } else if (card === 10 || card === 'J' || card === 'Q' || card === 'K' || card === 'A'){
        count--;
      }else {
        //Either just return or alert an error message and return
      }