Basic JavaScript - Counting Cards

Tell us what’s happening:
Describe your issue in detail here.
I don’t understand why count = count++ is not considered correct, only count++ is? Same goes for count = count-- vs count–
I thought they both represent the same thing?
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 =  count++;
    case 7:
    case 8: 
    case 9: 
     count = count;
    case 10:
    case 'J':
    case 'Q':
    case 'K':
    case 'A':
    count =  count--;
 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 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Safari/605.1.15

Challenge: Basic JavaScript - Counting Cards

Link to the challenge:

Well that’s because count++ is actually doing two operations:

count = count + 1;

You are first adding one to count’s current value and then assigning that result to the same variable count.
Doing the following:

count = count++;

Is adding nothing to the execution of your code, you would just be reassigning the same value to the same variable.
The same goes for count--.

Thanks for your reply. However I’m still confused…isn’t count++ an abbreviation for count + 1? In which case count = count + 1 is exactly the same as count = count++ (adding 1 to count → reassigning the new value to the count variable)??
Am I misunderstanding something??

count++ is equivalent to count = count + 1, so I guess count = count++ would be equivalent to count = count = count + 1.

Actually, it is a bit more complicated than that. Consider the following code:

let a = 2;
let b = 5;

a = b++;
console.log(a); // 5
console.log(b); // 6

The line a = b++; adds 1 to b, and assigns the original value of b to a, so a == 5. Now look at this code:

let a = 2;
let b = 5;

a = ++b;  // <-- this line is different!
console.log(a); // 6
console.log(b); // 6

In this case, b is incremented by 1, and the new value is assigned to a, so they are both equal to 6.

Therefore, if you really want to increment a variable in the way you described, you can do the following:

count = ++count;

However, I do not see a good reason to do so.

The order matters here. Google ‘prefix vs postfix increment’.

Generally, you should either use ++ OR use =

Yes! I was quoting a line from the code

Yes. I am aware.

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