Why is a number (number 4 in the video) entered in the console.log statement on the last line:
var count = 0;
function cc(card) {
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;
}
let holdbet = 'Hold';
if (count > 0) {
holdbet = 'Bet';
}
return count + ' ' + holdbet;
}
cc(2); cc('3'); cc(7); cc('A'); cc('K');
console.log(cc(4));
I’ve used the code on codepen and I can see the result changes if that number changes, but why is it there?
Hi
But the result takes into account all the values entered for cc above as well. Is the number 4 just adding one more value to calculation?
This returns a result based on the values given before the last line:
console.log(cc());
so no value in the argument works fine too…
It’s just all so extremely confusing! Thank you for bothering to answer.
your count variable is Global, meaning it is declared outside the function cc() but you are modifying the value of it inside cc(). So each and every time you modify count inside cc(), it will keep it’s value and next time you modify it, it will just append to its previous value.
If you do not want that behavior, then move your count variable inside cc(). If you want it to be global, still this is bad coding practice as everyone have access to count and it can be modified unintentionally and you will observe strange results. In such situations it is good to use a Closure