Basic JavaScript - Counting Cards - What keeps the running count and allows for multiple inputs?

So, I’ve looked at the solution and the challenge is complete, but I want help in understanding how this keeps a “running” count- specifically how does this code account for multiple inputs? The way I understand it is- it allows for one input, and then it’s done. After inputting the first number, and then running it, what mechanism keeps the running count? I would think the program resets after each time it’s run.

For example, if the input is “2”, then we hit that in case 2, one increment is added to the count, then the output “+1 Bet” is returned, and the program is done, is it not? So if then, after doing that, a “4” is inputted, would it not return the same thing- “+1 Bet”, rather than what we want (the running count) of “+2 Bet”? Does it not just reset the program after each input? Sorry for the redundancy but I just want to be as clear as possible.

Also, why don’t we prompt the user to enter a card number or letter? I’m an extreme noob, but I have studied a little bit of other coding languages, and I remember us asking the user questions, but i haven’t seen any of that in this Javascript course.

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:
  count++;
  break;
  case 10:
  case "J":
  case "Q":
  case "K":
  case "A":
  count--;
  break;
}
if (count > 0) {
  return (count + " Bet");
} else {
  return (count + " Hold");
}
  // Only change code above this line
}

cc(2); cc(3); cc(7); cc('K'); cc('A');

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/117.0

Challenge: Basic JavaScript - Counting Cards

Link to the challenge:

The count is a global variable that is modified every time the function is called.

By calling the function, you are assuming the caller knows what the function is for. User input is a separate, more complicated subject.

Ok, I see, since the count variable is outside of the function, it’s global and is updated each time after the program is run. So, would it be appropriate to say that in my 2nd paragraph example that I edited in after posting, that after the program is run one time, then the “new” code that is now present and ready to be run when faced with a second input is:

Exactly the same as it started, EXCEPT the very top now would read (if we could see it) :

let count = 1;

instead of the previous:

let count = 0;


Is that the right way to think about it?

There is no “new” code. The function is defined once and then it runs multiple times. Each time it runs, it updates the value of the global variable count.

1 Like

Alright, thank you very much for your responses! I hope you have a good day.

1 Like

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