var myVar = 11;
myVar- -; /* without space between minuses */
why is myVar not 10 now
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);
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.
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
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.
Yeah, I generally recommend that you write your code so that postfix and prefix incrementing/decrementing doesn’t come into play.
thx so much!!!
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.