Basic JavaScript - Counting Cards

Tell us what’s happening:
Describe your issue in detail here.

I have solved this problem and the code I wrote works, but why it is working the way it works makes no sense to me at all and i really do not want to waste anymore time on it.Hence me, asking for help.

I expect that for each call of the function , there is either an increment or decrement for count. I expect the function to output a return statement/value for every single call of the function. The way the code is working now, the 5 function calls occur all at once and return a single value instead of 5 function calls returning 5 separate values since the switch statement will only run once for every single function call. I beg anyoine to please kindly explain what is going on?

I am also thinking that perharps there is some background recursive function call or for-loop running in the freecodecamp IDE that I can not see at the moment.

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+=1;
      break;
    case 7:
    case 8:
    case 9:
      count+=0;
      break;
    case 10:
    case "J":
    case "Q":
    case "K":
    case "A":
      count-=1;
      break;
  }
  
  if(count>0){
    return count+" "+"Bet";
  }else if(count<=0){
    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) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Counting Cards

Link to the challenge:

Hi there and welcome to our community!

I have spoilered your solution for the benefit of anyone who is yet to solve this.
The count variable is in the global scope (i.e. outside of the function), which means that each time that the function is called, the value of count will indeed be incremented/decremented accordingly.

If you were to console.log(count) after each function call, you would see that its value changes each time. Also, if you were to console.log() each function call, you’d see the returned value from the function each time (which is otherwise invisible).

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