Um..why is this not working?

var myVar = 11;

myVar- -; /* without space between minuses */

why is myVar not 10 now

Where are you testing for the output? You should be able to see it printed as 10 if you run:

var myVar = 11;
myVar--;
console.log(myVar);
1 Like

Decrement (–) operator used after the operand (myVar in your example) returns the current value first, then subtracts by one. To answer your question: it works the way you told it to work - return the value, decrement by one. If you logged the value, you’d see it’s 10.

1 Like

Just to be clear, you have to log it after the decrement. If you just log myVar-- you will, as already explained, see the current value before the postfix decrement.

var myVar = 11;
myVar--;
console.log(myVar); // 10
console.log(myVar--); // 10
console.log(myVar); // 9
1 Like

And just to be clear, if you read the link that lasjorg provided, if you put the -- before the variable, it will decrement, then evaluate, getting the result you were expecting:

var myVar = 11;
console.log(--myVar); // 10

But I think that when you start doing that, code gets less readable so I would be careful about using that too much.

1 Like

Yeah, I generally recommend that you write your code so that postfix and prefix incrementing/decrementing doesn’t come into play.

2 Likes

thx so much!!!

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