This is because numero--
returns the value of numero
before to decrement it:
var numero = 10;
console.log(numero); // 10
// primeiro retorna o valor atual (10) e depois decrementa
console.log(numero--); // 10
// depois de decrementado
console.log(numero); // 9
If you want to return the value after the decrease, just use --numero
:
var numero = 10;
console.log(numero); // 10
var diminuirNumero = --numero;
console.log(diminuirNumero); // 9
For thus the number is first decreased, and then the result is returned:
var numero = 10;
console.log(numero); // 10
// primeiro decrementa e depois retorna o valor (9)
console.log(--numero); // 9
// depois de decrementado
console.log(numero); // 9
More details on documentation and in the language specification <- in fact, this link has a detailed description of this behavior:
Postfix Decrement Operator
UpdateExpression:LeftHandSideExpression--
- Let
lhs
be the result of evaluating LeftHandSideExpression
.
- Let
oldValue
be ToNumeric(GetValue(lhs))
.
- Let
newValue
be Type(oldValue)::subtract(oldValue, Type(oldValue)::unit)
.
- Perform
PutValue(lhs, newValue)
.
- Return
oldValue
.
Prefix Decrement Operator
UpdateExpression:--UnaryExpression
- Let
expr
be the result of evaluating UnaryExpression
.
- Let
oldValue
be ToNumeric(GetValue(expr))
.
- Let
newValue
be Type(oldValue)::subtract(oldValue, Type(oldValue)::unit)
.
- Perform
PutValue(expr, newValue)
.
- Return
newValue
.
That is, the postfix Operator (numero--
) returns the value the number had before the decrease, already the prefix Operator (--numero
) returns the value that the number has after the decrement is done. But both update the value of numero
.
Finally, if you do not want to change the value of numero
, then you do numero - 1
. And in this case it works because first the account is made numero - 1
, and then the result is assigned to diminuirNumero
.
The 3 answers are identical, I will mark as accepted the oldest answer ;-)
– user60252