Question about JS switch and break;

The counting cards exercise, it’s the 80th one from Basic Javascript
Why does it return on the last function call cc(‘A’)? Why doesn’t it break like every call prior to it? The switch statements have break; in them so how does it get past the switch to the if statement? Thanks.

> var 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:
>       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');

Hi there!

Firstly switch are just like if statements. The break signifies the end of each condition. So when you call the function cc(2). It goes through the switch first to see if the value 2 meets any of the condition there.

If you look at the switch, you will notice it does. because it has a case for 2.

What this means is if the value of card is either 2, 3, 4, 5 or 6, the count value should increase by one. So once 2 is passed into this function, the count which is 0 by default gets increased to 1.

Now since 2 doesn’t meet any of the other conditions on the switch, it leaves that section and move on to the if statement.

Now the count is 1 so it should return the first condition on the if statement because 1 > 0.

if you then add cc(3) the same thing happens again but this time the count value is now 1 because the cc(2) increased it to 1. 3 passes the condition on the switch so count is again increased by 1 so count = 2.

the code actually returns the value of the if statement every time. to see this just console.log() each case.

To make things easier I will quickly summarize what is going on. Below shows the value of count in each case! From default to cc("A)

countDefault cc(2); cc(3); cc(7); cc('K'); cc('A');
0 +1 +1 +0 -1 -1

So by the time cc(“A”) runs, the count value is equal to — 0.
Because 0 + 1 + 1 + 0 - 1 - 1 = 0

If you console.log(cc(A)) it should return ---- “0 Hold”

Hope this helps

there are 5 function calls there, each one with its output. as there is a function for each card draw, and it’s the last one that is intresting, then the last function call is the one for which the output is tested