Basic JavaScript - Counting Cards

I’m stuck because my code can’t fix this Every other challenge runs well:

Cards Sequence 2, J, 9, 2, 7 should return the string 1 Bet

Cards Sequence 2, 2, 10 should return the string 1 Bet

Your code so far

let count = 0;

function cc(card) {
  // Only change code below this line
  switch(card){
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
      return ++count + " Bet";
      break;
    case 7:
    case 8:
    case 9:
      return count + " Hold";
      break;
    case 10:
    case "J":
    case "Q":
    case "K":
    case "A":
      return --count + " Hold";
      break;
  }
  // Only change code above this line
}
cc(2); cc("J"); cc(9); cc(2); console.log(cc(7));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Counting Cards

Link to the challenge:

Hi there and welcome to the forum!

Your logic is not quite correct.

As there is a global count variable, it means that the value of count will change each time the function is invoked, and won’t be reset to 0 each time. So, after a sequence of cards, count could have been incremented/decremented a number of times.

The ‘Bet’ or ‘Hold’ message should depend on the current value of count. For instance, even if a particular card decrements count, the value of count could still be positive, so returning ‘Hold’ would be inaccurate.

You will need to check the value of count to check which message you should be returning.

1 Like

Thanks for the help. I have modified it this way and it works

let count = 0;

function cc(card) {
  // Only change code below this line
  switch(card){
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
       ++count;
      break;
    case 7:
    case 8:
    case 9:
       count;
      break;
    case 10:
    case "J":
    case "Q":
    case "K":
    case "A":
      --count ;
      break;
  }
  if(count < 0){
    return count + " Hold";
  }
  else if(count === 0){
    return count + " Hold";
  }
  else {
    return count + " Bet";
  }

  // Only change code above this line
}
cc(2); cc("J"); cc(9); cc(2); console.log(cc(7));

Great :+1:
I’ve spoilered your solution, for anyone who hasn’t yet solved this challenge.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.